Perl 脚本获取作为引用传递的数组的第一个元素
我想通过向子例程传递大约 4 个数组来调用子例程,然后获取每个数组的第一个值,然后在子例程中创建一个新数组(传递的数组的第一个元素的数组),然后返回该数组。这是我尝试使用的代码,
my @a = (97,34,6,7);
my @b = ("A", "B", "F", "D");
my @c = (5..15);
my @d = (1..10);
my @tailings = popmany ( \@a, \@b, \@c, \@d );
print @tailings;
sub popmany {
my @retlist = ();
for my $aref (@_) { #1
my $arrele = @$aref; #2
push @retlist , $arrele #3
}
return @retlist;
}
在#1中我使用循环并获取第一个数组,然后在第2行中我将整个数组分配给一个变量,认为默认情况下perl只会将数组的第一个变量存储到@中阿雷莱。我将 $arrele 推送到一个新数组 @retlist ,抱歉我没有引用任何注释,所以我的程序可能是错误的。但这给了我一个类似的输出 441110
这没有任何意义。
请解释一下代码我该怎么做。
I want to call a subroutine by passing around 4 arrays to it and then get the first value of each array and then create a new array(array of first elements of arrays that are passed) in the subroutine and then return back that array. Here is the code I tried with
my @a = (97,34,6,7);
my @b = ("A", "B", "F", "D");
my @c = (5..15);
my @d = (1..10);
my @tailings = popmany ( \@a, \@b, \@c, \@d );
print @tailings;
sub popmany {
my @retlist = ();
for my $aref (@_) { #1
my $arrele = @$aref; #2
push @retlist , $arrele #3
}
return @retlist;
}
Here in #1 I use a loop and get the first array , then in line 2 I assign the whole array to a variable, thinking that by default the perl will only store the first variable of array into @arrele. the I push the $arrele to a new array @retlist , Sorry I dint refer any notes, so my procedure might be wrong. But this is throwing me a output like
441110
which has no sense.
Please explain me the code how can I do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在这里:
您要求 perl 将
@{$aref}
放入标量上下文中,它返回 $aref 指向的数组的长度(其中的元素数量)。相反,尝试:
它将访问数组的第一个元素。
It's here:
where you're asking perl to put
@{$aref}
into scalar context, which returns the length (number of elements in) the array pointed at by $aref.Instead try:
which will access the first element of the array instead.
该行将
@$aref
数组的长度分配给$arrele
。要获取数组的第一个元素,您可以使用以下任意一种:另外,由于您基于另一个列表生成列表,因此可以使用
map
:The line
assigns the length of the
@$aref
array to$arrele
. To get the first element of the array you could use any of:Also, since you generate a list based on another list, you could use
map
:更简单地写为
Far more simply written as