3 Perl - 列表赋值 - 将数组插入字符串

来源:互联网 发布:拍卖系统安卓as源码 编辑:程序博客网 时间:2024/06/05 18:27

将数组插入字符串


和标量类似,数组也可以插入双引号的字符串中。插入的数组元素会自动由空格◆分开:
◆分隔符是变量$’’的值,其默认值为空格(space)。


@rocks = qw{ flintstone slate rubble };
print “quartz @rocks limestone/n”; #输出为5 种rocks 由空格分开


插入的数组元素的第一个元素前面和最后一个元素后面不会插入空格,如果需要可以自己加入:


print “Three rocks are: @rocks./n”;
print “There’s nothing in the parens (@empty) here../n”;


如果忘了数组插入的规则,当把email 地址插入双引号字符串时可能出现意想不到的结果。由于历史原因◆,这将引起编

译时的严重错误:
◆你可能会问:在Perl5 之前,Perl 将不会替换没有定义过的数组标量。因此,“fred@bedrock.edu” 将表示email 地址。但当某人加入了一
个变量@bedrock;则这字符串将变成“fred.edu”或者更糟。

 

$email =“fred@bedrock.edu”; #错误!将会替换@bedrock
$email =“fred/@bedrock.edu”; #正确
$email =‘fred@bedrock.edu’; #另一种方法

 

。如果想在一个标量变量后接一个左中括号符,那应当在其间加入分隔符,否则会被作为数组看待:

@fred = qw(eating rocks is wrong);
$fred = “right”; #我们将打印“this is right[3]”
print “this is $fred[3]/n”; #打印出“wrong”使用$fred[3]
print “this is ${fred}[3]/n”; #打印出“right”(由花括号分开)
print “this is $fred”. “[3]/n”; #正确(两个字符串,右. 分开)
print “this is $fred/[3]/n”; #正确(利用反斜线转义)