Perl中my ($variableName)
和my $variableName
之间有什么区别?括号怎么办?
答案 0 :(得分:20)
重要的效果是在声明变量的同时初始化变量:
my ($a) = @b; # assigns $a = $b[0]
my $a = @b; # assigns $a = scalar @b (length of @b)
另一个重要的是当你声明多个变量时。
my ($a,$b,$c); # correct, all variables are lexically scoped now
my $a,$b,$c; # $a is now lexically scoped, but $b and $c are not
如果您use strict
,最后一条语句会给您一个错误。
答案 1 :(得分:5)
有关my
运算符的详细信息,请查看perdoc perlsub。这是一个小摘录:
梗概:
my $foo; # declare $foo lexically local
my (@wid, %get); # declare list of variables local
my $foo = "flurp"; # declare $foo lexical, and init it
my @oof = @bar; # declare @oof lexical, and init it
my $x : Foo = $y; # similar, with an attribute applied
答案 2 :(得分:5)
简短的回答是,在=
的左侧使用括号时强制列表上下文。
其他每个答案都指出了一个特殊情况,这会产生影响。实际上,您应该通读perlfunc以更好地了解函数在列表上下文中调用时的行为方式,而不是标量上下文。
答案 3 :(得分:2)
正如另一个答案和评论所解释,括号的用法为变量提供了列表上下文。
下面是一段代码片段,它通过使用perl函数split
提供了更多解释
use strict;
my $input = "one:two:three:four";
# split called in list context
my ($out) = split(/:/,$input);
# $out contains string 'one'
#(zeroth element of the list created by split operation)
print $out,"\n";
# split called in scalar context
my $new_out = split(/:/,$input);
# $new_out contains 4 (number of fields found)
print $new_out,"\n";
use strict;
my $input = "one:two:three:four";
# split called in list context
my ($out) = split(/:/,$input);
# $out contains string 'one'
#(zeroth element of the list created by split operation)
print $out,"\n";
# split called in scalar context
my $new_out = split(/:/,$input);
# $new_out contains 4 (number of fields found)
print $new_out,"\n";