start page | rating of books | rating of authors | reviews | copyrights

Book HomeLearning Perl, 3rd EditionSearch this book

3.5. 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[79] upon interpolation:

[79]Actually, the separator is the value of the special $"variable, which is a space by default.

@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. For historical reasons,[80] this is a fatal error at compile time:

[80]Since you asked: Before version 5, Perl would silently leave uninterpolated an unused array's name in a double-quoted string. So, "[email protected]" might be a string containing an email address. This attempt to Do What I Mean will backfire when someone adds a variable named @bedrockto the program -- now the string becomes "fred.edu" or worse.

$email = "[email protected]";  # WRONG! Tries to interpolate @bedrock
$email = "fred\@bedrock.edu"; # Correct
$email = '[email protected]';  # 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. In other words, if $y contains the string "2*4", we're still talking about element 1, not element 7, because "2*4" as a number (the value of $y used in a numeric expression) is just plain 2.[81]

[81]Of course, if you've got warnings turned on, Perl is likely to remind you that "2*4"is a pretty funny-looking number.

If you want to follow a simple scalar variable with a left square bracket, you need to delimit the square bracket so that it isn't considered part of an array reference, as follows:

@fred = qw(eating rocks is wrong);
$fred = "right";               # we are trying to say "this is right[3]"
print "this is $fred[3]\n";    # prints "wrong" using $fred[3]
print "this is ${fred}[3]\n";  # prints "right" (protected by braces)
print "this is $fred"."[3]\n"; # right again (different string)
print "this is $fred\[3]\n";   # right again (backslash hides it)


Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.