从Perl子程序返回多个数组

时间:2019-03-22 12:35:48

标签: perl subroutine

我给perl子例程四个参数,该例程使用它们创建两个单独的数组@temp_V@temp_t。当我尝试将它们返回到主程序时,不再有两个单独的数组。相反,@temp_t中的值附加了@temp_V,从而为我提供了一个数组。

如何解决此问题?这是我的代码:

$Vmin=-5;
$Vmax=5;
$N_pulses=5;
$Freq=25e3;

my (@V, @t)=create_FORC($Vmin,$Vmax,$Freq,$N_pulses);

print "@V \n\n\n"; 
#print "@t \n"; 

sub create_FORC($Vmin,$Vmax,$Freq,$N_pulses)
{
my $Vmin=shift;
my $Vmax=shift;
my $Freq=shift;
my $N_pulses=shift;

my $rtime=1/(4*$Freq);
#print "$rtime \n";

undef @temp_V;
undef @temp_t;

push(my @temp_V,0);
push(my @temp_t,0);

push(@temp_V,$Vmin);

      for (my $pulse=0;$pulse<$N_pulses;$pulse++)
      {
      $V_peak=($Vmax-$Vmin)/$N_pulses*($pulse+1)+$Vmin;
      $del_t=($V_peak-$Vmin)*$rtime;  
          push(@temp_V,$V_peak); 
          push(@temp_V,$Vmin);  
          push(@temp_t,$del_t);
      } 
 push(@temp_V,0);

 print "@temp_V \n";
 print "@temp_t \n";

return (@temp_V, @temp_t); 

}

3 个答案:

答案 0 :(得分:5)

不能。当您从子目录返回内容时,Perl将返回一个列表。没有关于从子中出来之前数组中有多少元素的信息。

在Perl中列表是平坦的。它们不能嵌套。

(1, 2, (3, 4), ((), 5, (6)), 7)

这等效于:

(1, 2, 3, 4, 5, 6, 7)
((1), (2), (3), (4), (5), (6), (7))

如果要返回两个不同的数组,则需要返回对其的引用。

sub foo {
    my @bar = qw/a b c/;
    my @qrr = qw/1 2 3/;

    return \@bar, \@qrr;
}

my ($letters, $numbers) = foo();

然后可以将它们取消引用到数组变量中,或直接访问它们。

有关参考的更多信息,请参见perlreftutperlref

答案 1 :(得分:3)

返回对数组的引用:

return \@temp_v, \@temp_t

分配给实数组时,需要取消引用它们:

my ($V_ref, $t_ref)=create_FORC($Vmin,$Vmax,$Freq,$N_pulses);

然后使用@$V_ref代替@V(对于@$t_ref@t也是如此)。

您不能同时分配两个数组,因为赋值右侧的列表变平,而第一个数组本身就占用了所有值。

答案 2 :(得分:2)

数组不能传递给subs,只能传递给多个标量。

subs不能返回数组,只能返回多个标量。

这样做的时候

return ( @temp_V, @temp_t );

您将返回两个数组的内容,就好像您已经完成了

return ( $temp_V[0], $temp_V[1], ..., $temp_t[0], $temp_t[1], ... );

Perl不知道将多少项分配给呼叫者的@V,将多少项分配给呼叫者的@t,因此它将所有内容都分配给@V

解决方案是返回对数组的引用(因为引用是标量)。

return ( \@temp_V, \@temp_t );

然后呼叫者成为

my ($V, $t) = create_FORC($Vmin, $Vmax, $Freq, $N_pulses);

print "@$V\n\n@$t\n"; 
相关问题