在Perl中传递数组

时间:2014-02-26 11:55:45

标签: arrays perl

我现在有这个:

sub first_sub
{
    my @my_array;

    ## The second sub will return my_array filled out!
    second_sub (\@my_array);

    ## Array ok ... filled out!
}

但是,如果我想/需要将数组从second_sub传递到另一个子例程呢?例如:

sub first_sub
{
    my @my_array;

    ## The second sub will return my_array filled out!
    second_sub (\@my_array);
    ## ...
}

sub second_sub
{
    my $my_array = shift;

    ## The second sub will return my_array filled out!
    second_sub (my_array);   ## Passed by value ...

    ## Array empty here (because passed by value, right?) !!!
}

3 个答案:

答案 0 :(得分:2)

你通过调用子程序

犯了一个错误
second_sub (my_array); # By the way, use miss there the $ or @`

你通过引用而不是价值来原谅它。当缺少$时。

如果您想按值覆盖它,请使用:

second_sub (@{$my_array});

当您需要引用时,将其视为普通数组:

通过引用传递:

#!/usr/bin/perl

use strict;
use warnings;

sub first_sub {

    my @numbers = (1..10);
    second_sub(\@numbers);
}

sub second_sub {
    my $array_ref = shift;
    foreach (@{$array_ref}) {

        # Treat it like a normal array here
        print $_;
    }
}

first_sub();

按值传递:

#!/usr/bin/perl

use strict;
use warnings;

sub first_sub{

    my @numbers = (1..10);
    second_sub(@numbers);
}

sub second_sub {
    my @arrayParameter = @_;
    print "@arrayParameter\n";
}

first_sub();

答案 1 :(得分:2)

在标量变量中有数组引用之后,您可以根据需要在子例程之间传递它。

您的示例代码严重破坏,但我认为您的意思是这样的

first_sub();

sub first_sub {
  my @my_array;

  ## second_sub will fill out @my_array

  second_sub (\@my_array);   ## passed by reference

  print join(', ', @my_array), "\n";
}

sub second_sub {
  my ($my_array) = @_;     ## received by reference

  ## third_sub will fill out @my_array

  third_sub ($my_array);   ## passed by reference
}

sub third_sub {
  my ($my_array) = @_;     ## received by reference

  @$my_array = qw/ a b c d e /;
}

<强>输出

a, b, c, d, e

答案 2 :(得分:0)

使用:

sub first_sub {
    my @my_array;

    ## The second sub will return my_array filled out!
    second_sub (\@my_array);
    ## ...
}

sub second_sub {
    my $my_array = shift;

    ## The second sub will return my_array filled out!
    foreach my $newvar (@$my_array) {
        push (@new_array, $newvar);
    }   
}

这将填充上一个子例程中的新数组。