swa*_*rak 1 arrays perl reference multidimensional-array
当我想将输入文件分配给数组时,出现此错误。
while (<>) {
my @tmp = split;
push my @arr,[@tmp];
print "@arr\n";
}
output: ARRAY(0x7f0b00)
ARRAY(0x7fb2f0)
Run Code Online (Sandbox Code Playgroud)
如果我更改[为,(那么我将获得所需的输出。
while (<>) {
my @tmp = split;
push my @arr,(@tmp);
print "@arr\n";
output: hello, testing the perl
check the arrays.
Run Code Online (Sandbox Code Playgroud)
(@tmp)和之间的区别是什么[@tmp]?
普通括号()除了改变优先级外没有特殊功能。它们通常用于限制列表,例如my @arr = (1,2,3)方括号返回数组引用。在您的情况下,您将构建一个二维数组。(你会的,如果你的代码没有被破坏)。
你的代码也许应该这样写。请注意,您需要在循环块之外声明数组,否则它不会保留先前迭代的值。同时,你不需要使用注意@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
}
Run Code Online (Sandbox Code Playgroud)
该数组将具有以下结构:
$arr[0] = [ "hello,", "testing", "the", "perl" ];
$arr[1] = [ "check", "the", "arrays." ];
Run Code Online (Sandbox Code Playgroud)
例如,如果您想防止输入行混淆,这是一个好主意。否则,所有值都会在数组的同一级别中结束。