Strings
Non-interpolating strings
If you don't want interpolation, use single-quotes:
- print 'You may have won $1,000,000';
Or you can escape the special characters (sigils):
- print "You may have won \$1,000,000";
Be careful with email addresses in strings
This email address won't be what you want it to be:
- my $email = "andy@foo.com";
- # Prints "andy.com"
The problem is that is interpolated as an array. This problem is obvious if you have use warnings
turned on:
- my $email = 'andy@foo.com';
- my $email = q{andy@foo.com};
or escape the @
- my $email = "andy\@foo.com";
A good color-coding editor will help you prevent this problem in the first place.
- my $str = "Chicago Perl Mongers";
- print length( $str ); # 20
Use substr() to extract strings
does all kinds of cool string extraction.
Don't worry (too much) about strings vs. numbers
Unlike other languages, Perl doesn't know a "string" from a "number". It will do its best to DTRT.
- my $phone = "312-588-2300";
- my $exchange = substr( $phone, 4, 3 ); # 588
- print sqrt( $exchange ); # 24.2487113059643
- $ cat foo.pl
- $a = 'abc'; $a = $a + 1;
- $b = 'abc'; $b += 1;
- print join ", ", ( $a, $b, $c );
- $ perl -l foo.pl
- 1, 1, abd
Note that you must use the ++
operator. In the other two cases above, the string "abc"
is converted to and then incremented.
Create long strings with the '' operators
You can create long strings with the ''
operators
Create long strings with heredocs
Heredocs are
- Allows unbroken text until the next marker
- Interpolated unless marker is in single quotes
- my $page = <<HERE;
- <html>
- <head><title>$title</title></head>
- <body>This is a page.</body>
- </html>
- HERE
XXX Discuss dangers of heredocs.