将变量传递给Perl子例程

时间:2013-02-27 10:38:03

标签: perl

我想将以下变量传递给子例程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]@_,但我似乎没有将变量正确地传递给子程序。

3 个答案:

答案 0 :(得分:26)

有几种方法可以做到这一点(就像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);

答案 1 :(得分: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子程序)。

答案 2 :(得分:5)

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

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中数组的更改会影响原始数据,但是:

sub array_by_ref {
    my $array_ref = shift;

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

array_by_ref(\@original_array);