Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

Interpolating Arrays into Strings

Like scalars, array values may be interpolated into a double-quoted string. Elements of an array are automatically separated by spaces[*] upon interpolation:

@rocks = qw{ flintstone slate rubble };
print "quartz @rocks limestone\n";  # prints five rocks separated by spaces

There are no extra spaces added before or after an interpolated array; if you want those, you’ll have to put them in yourself:

print "Three rocks are: @rocks.\n";
print "There's nothing in the parens (@empty) here.\n";

If you forget that arrays interpolate like this, you’ll be surprised when you put an email address into a double-quoted string:

$email = "fred@bedrock.edu";  # WRONG! Tries to interpolate @bedrock

Although we intended to have an email address, Perl sees the array named @bedrock and tries to interpolate it. Depending on our version of Perl, we’ll probably just get a warning:[]

Possible unintended interpolation of @bedrock

To get around this problem, we either escape the @ in a double-quoted string or use a single-quoted string:

$email = "fred\@bedrock.edu"; # Correct
$email = 'fred@bedrock.edu';  # Another way to do that

A single element of an array will be replaced by its value, just as you’d expect:

@fred = qw(hello dolly);
$y = 2;
$x = "This is $fred[1]'s place";    # "This is dolly's place"
$x = "This is $fred[$y−1]'s place"; # same thing

Note that the index expression is evaluated as an ordinary expression, as if it were outside a string. It is not variable-interpolated first. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page