user2114919
user2114919

Reputation: 157

Passing variables to a Perl subroutine

I would like to pass the following variables to subroutine mySubroutine, $name, $age and then this multidimensional array:

$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;

Subroutine:

sub mySubroutine
{

}

I have tried $_[0], and @_, but I don't seem to get the variables passed to the subroutine correctly.

Upvotes: 12

Views: 87538

Answers (3)

Krishnachandra Sharma
Krishnachandra Sharma

Reputation: 1342

Another way, which passes the array by reference, but then makes a copy of it to avoid changing the original when you edit it.

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);

For a better understanding, please refer to perlsub (Perl subroutines).

Upvotes: 6

user1919238
user1919238

Reputation:

Another option, as long as you are only passing one array, is to pass it normally by value as the last element:

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);

However, it is most efficient to avoid any additional copy of the array by only using a reference within the sub. This does mean that changes to the array in the sub affect the original, however:

sub array_by_ref {
    my $array_ref = shift;

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

array_by_ref(\@original_array);

Upvotes: 5

m0skit0
m0skit0

Reputation: 25874

There are several ways to do it (like most things in Perl). I personally do it like this:

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);

Upvotes: 27

Related Questions