Strings

    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. # Prints "andy.com"

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

    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.

    1. my $str = "Chicago Perl Mongers";
    2. 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.

    1. my $phone = "312-588-2300";
    2.  
    3. my $exchange = substr( $phone, 4, 3 ); # 588
    4. print sqrt( $exchange ); # 24.2487113059643
    1. $ cat foo.pl
    2. $a = 'abc'; $a = $a + 1;
    3. $b = 'abc'; $b += 1;
    4.  
    5. print join ", ", ( $a, $b, $c );
    6.  
    7. $ perl -l foo.pl
    8. 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
    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.