perl,函数只打印数组的第一个元素

时间:2014-08-22 17:15:05

标签: perl

我有一个数组,其上有几个元素但是当我将数组作为参数传递给函数然后调用该函数时,它只会多次打印出数组的第一个元素。例如

my $element;
my $random_variable = "Testing";
my @the_array = ("hello", "bye", "hey");

foreach $element(@the_array)
{
  PrintFunction(@the_array, $random_variable)
}

sub PrintFunction{
 my ($the_array, $random_variable) = @_;
 // other code here

 print $the_array . "\n";

}

我从中得到的结果是

hello
hello
hello

我想要的结果是将数组的所有元素打印为

hello
bye
hey

2 个答案:

答案 0 :(得分:3)

变化:

  PrintFunction(@the_array, $random_variable)

为:

  PrintFunction($element, $random_variable)

您的代码将整个数组传递给sub,然后您每次只打印数组的第一个元素,因为您在sub中使用了标量变量$the_array。由于foreach抓取了数组的每个元素,因此您可能需要使用$element

答案 1 :(得分:1)

Print @_;添加到您的子网以查看传递给它的内容。你会看到:

hellobyeheyTesting
hellobyeheyTesting
hellobyeheyTesting

这意味着您传递整个数组,后跟$random_variable。因此,$the_array中的sub将始终是@the_array的第一个元素,即hello。要解决这个问题,你应该通过

迭代地传递数组的每个元素
foreach $element(@the_array)
{
  PrintFunction(@element, $random_variable)
}
相关问题