脚本语言,Oracle数据库集群,软件测试,开源软件
[Perl] 数组的访问
上一篇 /
下一篇 2007-05-24 07:44:15
/ 个人分类:Perl
Perl中的数组是一个让我这个初学者有些糊涂的地方。比如说数组元素的访问,Perl中的数组的访问使用这样的语法:
初看上去像是在一个标量变量之后加上一个由方括号括起来的索引值。但是,当你想要引用整个数组的时候,Perl给出的语法却是:
| @fred = qw(eating rock is wrong); |
这里是“@”加上数组名“fred”。
接下来看看下面这段代码:
@fred = qw(eating rock is wrong);
$fred = "right";
print "this is $fred[3]\n";
print "this is ${fred}[3]\n";
print "this is $fred"."[3]\n";
print "this is $fred\[3]\n"; |
当“@fred”和“$fred”同时出现在这段代码中的时候,感觉是不是有点晕?让你正确地写出这段代码的运行结果是不是有点难?
其实上面这都是《Learning Perl》第4版中的示例,仔细阅读了书中相关的解释,我才理解了这些代码:
1、“@fred”和“$fred”中的2个“fred”,前一个是数组名,后一个是标量(scalar)变量名,两者来自完全不同的命名空间:
| The array name (in this case, "fred") is from a completely separate
namespace than scalars use. You could have a scalar variable named
$fred in the same program. Perl treats them as different things and
doesn't get confused. |
2、代码的运行结果是:
this is wrong this is right[3] this is right[3] this is right[3]
|
因为:
$fred[3]访问了数组的第4个元素;
${fred}[3]中的“fred”受到了花括号的保护;
“.”连接了2个不同的字符串:"this is $fred"和"[3]\n";
$fred\[3]中的“\”对“[”进行了转义。
导入论坛
收藏
分享给好友
管理
举报
TAG:
Perl