http://www.perlmonks.org?node_id=228829


in reply to Pass local array by reference?

Yes, you can pass another subroutine an array. You're title mentioned something about passing an array by reference. If you pass by reference, include a backslash before the @ symbol. Try this:
sub FOO { my @array; #code here #Here is the pass to BAR &BAR(\@array); } sub BAR { my(@array) = @_; #This will receive the array from FOO #code here }
If you send an array (or any other variable type) by reference, remember to dereference it. You can do this by placing the variable type symbol in front of the $ sign i.e. @$array, $$scalar, %$hash. Once a variable is dereferenced, you can use it like you normally would

Replies are listed 'Best First'.
Re: Re: Pass local array by reference?
by hmerrill (Friar) on Jan 21, 2003 at 21:02 UTC
    I prefer to call a "receiving" variable what it really is, so in subroutine BAR, I would do this:
    sub BAR { my $arrayref = shift; #This will receive the array *reference* from + FOO ### Then, I can refer to specific elements of the ### array using the arrayref: my $first_element = $arrayref->[0]; ### or by turning the arrayref back into an array: my @bar_array = @{$arrayref}; my $1st_element = $bar_array[0]; #code here }
    Remember, FOO is passing an array *reference* to BAR, so BAR receives an array *reference* - just my preference for clarity to include "ref" in the name of the variable so it's easy to tell what the variable contains. HTH.