3.5. Interpolating Arrays into StringsLike 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. For historical reasons,[] this is a fatal error at compile time:
$email = "fred@bedrock.edu"; # WRONG! Tries to interpolate @bedrock $email = "fred/@bedrock.edu"; # Correct $email = 'fred@bedrock.edu'; # Another way to do that However,in versions of Perl 5 soon to be released as we write this,the behavior of an unseen array variable will become similar to an unseen scalar variable,i.e.,replaced with an empty string with a warning if warnings are enabled. The Perl developers apparently figure that 10 years of fatality are enough warning. A single element of an array will be replaced by its value 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 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.[*] If you want to follow a simple scalar variable with a left square bracket,you need to delimit the square bracket so it isn't considered part of an array reference:
@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) |
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。