Strings
| Single and double quotes | |
| Concatenation and repetition | |
| length, substr, index | |
| Case and chomp |
Single and double quotes
Perl has two kinds of string literal with one important difference. Single quotes take the text as written: no variables, no escape sequences except a backslash before a quote or a backslash. Double quotes interpolate variables and understand escapes such as \n and \t.
Use single quotes when the text is data, double quotes when the text is a template.
my $name = "Ada";
print 'hello $name\n'; # prints hello $name\n
print "hello $name\n"; # prints hello Ada
perl demo.pl
hello $name\nhello Ada
The letters q and qq are the same two literals without the quote characters, which is handy when the text itself is full of quotes. The character after the letter becomes the delimiter.
my $name = "Ada";
print q{it's fine};
print qq{say "$name"\n};
perl demo.pl
it's finesay "Ada"
Concatenation and repetition
The dot joins strings and the letter x repeats them. Both have an assignment form that changes the left side in place.
my $greeting = "hello" . " world";
print "$greeting\n"; # hello world
$greeting .= "!";
print "-" x 20, "\n"; # --------------------
perl demo.pl
hello world
--------------------
length, substr, index
Three functions cover most string surgery. length counts characters, substr cuts a piece out, and index finds the position of a smaller string.
my $path = "/var/log/app.log";
print length $path, "\n"; # 16
print substr($path, 0, 4), "\n"; # /var
print index($path, "log"), "\n"; # 5
perl demo.pl
16
/var
5
substr also assigns: give it a replacement as the fourth argument and the original string changes. Negative offsets count from the end, so substr $path, -3 returns the extension.
my $path = "/var/log/app.log";
print substr($path, -3), "\n"; # log
substr($path, -3) = "txt";
print "$path\n"; # /var/log/app.txt
perl demo.pl
log
/var/log/app.txt
Case and chomp
Input from a file or a terminal almost always ends with a newline that you do not want. chomp removes exactly one trailing newline; chop removes the last character whatever it is, which is rarely what you mean.
Case conversion comes in three flavors, each returning a new string rather than changing the original.
my $line = " Hello World\n";
chomp $line;
print "[", uc $line, "]\n"; # [ HELLO WORLD]
print "[", lc $line, "]\n"; # [ hello world]
print "[", ucfirst lc $line, "]\n"; # [ hello world]
perl demo.pl
[ HELLO WORLD]
[ hello world]
[ hello world]
Leading spaces survive all of them, and the brackets show where the text begins. Use a regular expression from lesson 21 when you need to trim both ends.
Next: Interpolation and quoting
Article author: Arthur Isaev