方括号在Perl中按照推送语法表示什么?

时间:2009-07-14 00:32:50

标签: perl arrays reference

我在阅读脚本时遇到了这种语法。我不确定方括号的用途是什么。

push @data, [ split //, $line ]; #printing this array gives crap values

或者换句话说,上面和下面的区别是什么?

push @data, (split//, $line); #printing this gives actual values

有什么建议吗?

2 个答案:

答案 0 :(得分:13)

代码:

push @data, (split//, $line);

将当前行中的所有项目推送到@data

push @data, [split //, $line]; 

将对包含这些项的匿名数组的引用推送到@data

如果您只处理一个'$ line'值,那么使用前者 1 可能更有效,但是,如果您正在处理包含多行且您想要的文件为了区分内容所在的行,后者更有效。

考虑:

my @data; 
while( my $line = <$fh> ){
  push @data , ( split //,  $line ); 
}
use Data::Dumper; 
$Data::Dumper::Indent = 0; 
$Data::Dumper::Terse = 1;
print Dumper( \@data ); 

这将产生作为单独字符读入的所有字节,单个字符 包含它们的数组,即:

[ "a", "b" , "c" , "\n", "d", "e", "f" ]

当这反过来会做一些完全不同的事情时:

my @data; 
while( my $line = <$fh> ){
  push @data , [ split //,  $line ]; 
}
use Data::Dumper; 
$Data::Dumper::Indent = 0; 
$Data::Dumper::Terse = 1;
print Dumper( \@data ); 

而是将这样的行分组:

[ [ "a", "b", "c" , "\n" ], [ "d" , "e", "f" , "\n" ] ]

所以你以后可以更容易地以编程方式遍历它。

注意:

 push @data, ( split  //, $line ); 

  push @data, split //, $line; 

是等同的。

另外,

my @other  = ( 1,2,3 );
push @data, @other ;

push @data, 1,2,3; 

是等价的。

来自perldoc -f push

push ARRAY,LIST

Treats ARRAY as a stack, and pushes the values of LIST onto the end of ARRAY.  The length of ARRAY increases by the length of LIST.  Has the same effect as

           for $value (LIST) {
               $ARRAY[++$#ARRAY] = $value;
           }

but is more efficient.  Returns the number of elements in the array following the completed "push".

* 1:实际上,tbf,任何半脑的人都可能需要@data = split //, $line

答案 1 :(得分:4)

这是我answers之一:

push @data, [ split //, $line ];

@data是一个数组引用数组。 @data的每个元素都是对匿名数组的引用,其中的条目是$line中的字符。

另见perldoc perlreftut