12

我想将以下变量传递给子程序 mySubroutine,$name, $age然后是这个多维数组:

$name = "jennifer";
$age = 100;

$list[0][0] = "TEST NAME 2";
$list[0][1] = "TEST GROUP 2";
$[0][2] = 10;

$[1][0] = "TEST NAME 2";
$[1][1] = "TEST GROUP 2";
$[1][2] = 2;

子程序:

sub mySubroutine
{

}

我已经尝试过$_[0], 和@_,但我似乎没有正确地将变量传递给子例程。

4

3 回答 3

27

有几种方法可以做到这一点(就像 Perl 中的大多数事情一样)。我个人是这样做的:

sub mySubroutine
{
    # Get passed arguments
    my ($name, $age, $refList) = @_;

    # Get the array from the reference
    my @list = @{$refList};
    # Good to go
}

# You need to pass @list as reference, so you 
# put \@list, which is the reference to the array
mySubroutine($name, $age, \@list);
于 2013-02-27T10:41:30.360 回答
6

另一种方法是通过引用传递数组,然后复制它以避免在编辑时更改原始数组。

sub mySubroutine
{
    ## Retrieve name
    my $name = shift;

    ## Retrieve age
    my $age = shift;

    ## Retrieve list reference
    my $refList = shift;

    ## De-reference the list's scalar
    my @list = @{$refList};
    # Good to go
}

## Function call
mySubroutine($name, $age, \@list);

为了更好地理解,请参阅perlsub(Perl 子例程)。

于 2013-02-27T10:44:21.110 回答
6

另一种选择,只要您只传递一个数组,就是按值将其作为最后一个元素正常传递:

sub scalars_and_one_array {
    my $name = shift;
    my $age = shift;

    foreach my $element (@_)
    {
       # Do something with the array that was passed in.
    }
}

scalars_and_one_array($name,$age,@array);

但是,最有效的方法是仅通过在 sub 中使用引用来避免数组的任何额外副本。这确实意味着对子数组的更改会影响原始数组,但是:

sub array_by_ref {
    my $array_ref = shift;

    foreach my $element (@$array_ref)
    {
       # Changing $element changes @original_array!
    }
}

array_by_ref(\@original_array);
于 2013-02-27T10:56:05.200 回答