Strings

Embed strings in other strings with interpolation

Double-quoted strings can interpolate other variables inside.

  1. my $name = "Inigo Montoya";
  2. my $relative = "father";
  3.  
  4. print "My name is $name, you killed my $relative";

Non-interpolating strings

If you don't want interpolation, use single-quotes:

  1. print 'You may have won $1,000,000';

Or you can escape the special characters (sigils):

  1. 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:

  1. my $email = "andy@foo.com";
  2. print $email;
  3. # Prints "andy.com"

The problem is that @foo is interpolated as an array. This problem is obvious if you have use warnings turned on:

  1. $ perl foo.pl
  2. Possible unintended interpolation of @foo in string at foo line 1.
  3. andy.com

The solution is either to use non-interpolating quotes:

  1. my $email = 'andy@foo.com';
  2. my $email = q{andy@foo.com};

or escape the @

  1. my $email = "andy\@foo.com";

A good color-coding editor will help you prevent this problem in the first place.

Use length() to get the length of a string

  1. my $str = "Chicago Perl Mongers";
  2. print length( $str ); # 20

Use substr() to extract strings

substr() does all kinds of cool string extraction.

  1. my $x = "Chicago Perl Mongers";
  2.  
  3. print substr( $x, 0, 4 ); # Chic
  4.  
  5. print substr( $x, 13 ); # Mongers
  6.  
  7. print substr( $x, -4 ); # gers

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.

  1. my $phone = "312-588-2300";
  2.  
  3. my $exchange = substr( $phone, 4, 3 ); # 588
  4. print sqrt( $exchange ); # 24.2487113059643

Increment non-numeric strings with the ++ operator

You can increment a string with ++. The string "abc" incremented becomes "abd".

  1. $ cat foo.pl
  2. $a = 'abc'; $a = $a + 1;
  3. $b = 'abc'; $b += 1;
  4. $c = 'abc'; $c++;
  5.  
  6. print join ", ", ( $a, $b, $c );
  7.  
  8. $ perl -l foo.pl
  9. 1, 1, abd

Note that you must use the ++ operator. In the other two cases above, the string "abc" is converted to 0 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
  1. my $page = <<HERE;
  2. <html>
  3. <head><title>$title</title></head>
  4. <body>This is a page.</body>
  5. </html>
  6. HERE

XXX Discuss dangers of heredocs.


Want to contribute?

Submit a PR to github.com/petdance/perl101