[ 和 ( 在 perl 中的以下两个代码之间的区别?
difference between the following two codes of [ and ( in perl?
当我想将输入文件分配给数组时,出现此错误。
while (<>) {
my @tmp = split;
push my @arr,[@tmp];
print "@arr\n";
}
output: ARRAY(0x7f0b00)
ARRAY(0x7fb2f0)
如果我将 [
更改为 (
,那么我将获得所需的输出。
while (<>) {
my @tmp = split;
push my @arr,(@tmp);
print "@arr\n";
output: hello, testing the perl
check the arrays.
(@tmp)
和[@tmp]
有什么区别?
普通圆括号()
除了改变优先级外没有特殊作用。它们通常用于限制列表,例如my @arr = (1,2,3)
方括号 return 数组引用。在您的情况下,您将构建一个 two-dimensional 数组。 (如果您的代码没有被破坏,您会的)。
你的代码或许应该这样写。请注意,您需要在循环块外声明数组,否则它不会保留先前迭代的值。另请注意,您不需要使用 @tmp
数组,只需将 split
放在 push
.
中即可
my @arr; # declare @arr outside the loop block
while (<>) {
push @arr, [ split ]; # stores array reference in @arr
}
for my $aref (@arr) {
print "@$aref"; # print your values
}
此数组的结构为:
$arr[0] = [ "hello,", "testing", "the", "perl" ];
$arr[1] = [ "check", "the", "arrays." ];
例如,如果您希望避免混淆输入行,这是个好主意。否则所有的值都在数组的同一层。
当我想将输入文件分配给数组时,出现此错误。
while (<>) {
my @tmp = split;
push my @arr,[@tmp];
print "@arr\n";
}
output: ARRAY(0x7f0b00)
ARRAY(0x7fb2f0)
如果我将 [
更改为 (
,那么我将获得所需的输出。
while (<>) {
my @tmp = split;
push my @arr,(@tmp);
print "@arr\n";
output: hello, testing the perl
check the arrays.
(@tmp)
和[@tmp]
有什么区别?
普通圆括号()
除了改变优先级外没有特殊作用。它们通常用于限制列表,例如my @arr = (1,2,3)
方括号 return 数组引用。在您的情况下,您将构建一个 two-dimensional 数组。 (如果您的代码没有被破坏,您会的)。
你的代码或许应该这样写。请注意,您需要在循环块外声明数组,否则它不会保留先前迭代的值。另请注意,您不需要使用 @tmp
数组,只需将 split
放在 push
.
my @arr; # declare @arr outside the loop block
while (<>) {
push @arr, [ split ]; # stores array reference in @arr
}
for my $aref (@arr) {
print "@$aref"; # print your values
}
此数组的结构为:
$arr[0] = [ "hello,", "testing", "the", "perl" ];
$arr[1] = [ "check", "the", "arrays." ];
例如,如果您希望避免混淆输入行,这是个好主意。否则所有的值都在数组的同一层。