Wednesday, July 7, 2010

Passing arrays to perl subroutines

Finally when we receive thes values in@_ variable then we can not recognize if we had passed one array or two value arraysbecause finally it is getting merged into one.
o

If you want to work with and identify the individual lists passed to Perl, then you need to use references:

(@listc, @listd) = simplesort(\@lista, \@listb);

The leading \ character tells Perl to supply a reference, or pointer, to the array. A reference is actually just a scalar, so we can identify each list by assigning the reference to each array within our subroutine. Now you can write your subroutineas follows:

sub simplesort
{
my ($listaref, $listbref ) = @_;

# De-reference the array list
my (@lista) = @$listaref;
my (@listb) = @$listbref;
# Now you can play with both arrays.
}