In perl, it's easy to passing one array to other functions, or return to other functions. You can either just pass the array, or its reference to other functions/subroutines.

You can pass a reference to an array.

func1(\@array)

Or you can pass the elements of an array.

func(@array)

What about multiple arrays ? hashes?

Usually people get wrong on this:

    (@a, @b) = func(@c, @d);
or
    (%a, %b) = func(%c, %d);

What happens is that the function passes the elements of the array, not seperated by different arrays.

In above case,

 passes @c and @d to @a

not @c -> @a, @d -> @b

so it could be tricky unless you pass a reference like below:

 ($cref, $dref) = func(\@c, \@d);

Same for hashes.


If you want to modify the array (as opposed to just modifying the existing elements of the array), you need to pass a reference.

Here is an example shows how to use reference to change a hash's value in subroutine.

sub hash_sub
{
  my $h_ref   = $_[0];
  $h_ref->{'name'}="hash_sub"; # the key 'name' value changed in both subroutine and its parent
  %hash=%$h_ref; # this is also called dereference, the whole hash get copied
  $hash{'name'}="name in dereferenced hash"; # the value in its parent will not change.
}

Note: It can be more efficient to pass a reference for long arrays, since creating and putting one reference on the stack is faster than creating an alias for each element of a large array. This will rarely be an issue, though.

More you can find in Perldoc http://perldoc.perl.org/perlsub.html#Pass-by-Reference

 

Comments powered by CComment