InterpolationVariables occuring within a double quoted string are 'interpolated'.28 68-69 62-63$x = 4; $name = "Joe"; print "I am $name. I am $n years old.\n"; Very convenient.
Dollar Sign ($) is special.
SINGLE quoted strings take their contents
literally - no interpolation, no backslash interpretation.
At Sign (@) is special, too - more on this later.
Concatenation and ReplicationThere are two simple string operators: '.' and 'x' - dot/period and lower case x.Interpolation often works better than concatenation:$full = $first . " " . $last; # concatenated The x operator replicates the string n times. It is not used often but is very convenient to have when you need it.$full = "$first $last"; 23-24 55-56 66$divider = "-" x 40; $greet = "hello "; $n = 5; print $greet x $n;
Reading from the keyboardSTDIN must be capitalized.print "Name? "; # note - no newline here $name = <STDIN>; 33-34 70-71 65
This gets a line from the terminal keyboard up to a newline (Enter or Return). Note that the newline (\n) IS included at the end of the receiving variable. This prints (Try it!) the following:print "Your name is $name. Hello!\n"; This is not quite what you expect or want.Your name is Joe . Hello! Chopping and ChompingThe function 'chop' will remove the last character from $name regardless of what it is.The kinder and gentler 'chomp' will remove one newline at the end of $name. If the last character is not a newline it will have no effect at all.chop $name; Now we can rewrite the reading of the name from the keyboard like so:chomp $name; 34-35 116,122,541-542 66print "Name? "; $name = <STDIN>; chomp $name; print "Your name is $name. Hello!\n";
Integer/String ConversionPerl will generally do what you want and expect it will do.$n = "34"; print $n*3; # 102 $n = 34; print "hello" . $n; # hello34 print 123 x "3"; # 123123123 24 45 66-67
Exercises
|