如何获取取消引用的匿名数组的第 n 个元素? [英] How can I get the nth element of a dereferenced anonymous array?
问题描述
use strict;
my $anon = [1,3,5,7,9];
my $aref = [\$anon];
print "3rd element: " . $ { $aref } [2] . "\n";
我想通过 $aref
变量获取匿名数组 $anon
的第 n 个元素.在代码中,我想通过使索引为 2 来获取 $anon
的第三个元素,但它什么也没返回.如果我写 $ { $aref } [0]
然后它返回类似 REF(0x7fd459027ac0)
I'd like to get the nth element of the anonymous array $anon
over the $aref
variable. In the code I wanted to get the 3rd element of $anon
by making the index 2 but it returned nothing. If I write $ { $aref } [0]
then it returns something like REF(0x7fd459027ac0)
如何获得第 n 个,例如 $anon
的第 3 个元素?
How can I get the nth, for example the 3rd element of $anon
?
理由:
my @area = (
qw[1 3 5 7 9],
qw[2 4 6 8 0],
qw[a e i u o],
qw[b c d f g]
);
foreach my $row (@area) {
foreach my $cell (@$row)
{
# do some processing on the element
print $cell . " ";
}
print "\n";
}
推荐答案
如何获取解除引用的匿名数组的第 n 个元素?
How can I get the nth element of a dereferenced anonymous array?
您有太多引用运算符.您已经构建了一个三层深的嵌套结构,难怪您在导航时遇到问题
You have too many reference to operators. You have built a nested structure three levels deep and it's no wonder you're having trouble navigating it
问题是你的$anon
已经是一个匿名数组的引用.方括号 [...]
构造一个匿名数组并返回对它的引用
The problem is that your $anon
is already a reference to an anonymous array. Square brackets [...]
construct an anonymous array and return a reference to it
然后你有
my $aref = [\$anon]
它创建另一个对具有一个元素的数组的引用:对 scalar $anon
的引用.
which creates another reference to an array with one element: a reference to the scalar $anon
.
所以你已经构建了这个
$anon = [1, 3, 5, 7, 9]
$aref = [ \ [1, 3, 5, 7, 9] ]
所以
${$aref}[0] is \ [1, 3, 5, 7, 9]
${${$aref}[0]} is [1, 3, 5, 7, 9]
${${${$aref}[0]}}[2] is 5
但是为什么要使用对数组的引用,尤其是对标量的引用?最好从普通数组开始,写
But why are you working with references to arrays at all, and especially references to scalars? It would be best to begin with an ordinary array, and write
my @array = ( 1, 3, 5, 7, 9 );
my $aref = \@array;
print $aref->[2];
输出
5
这篇关于如何获取取消引用的匿名数组的第 n 个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!