Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Pass local array by reference?

by Anonymous Monk
on Jan 21, 2003 at 19:44 UTC ( [id://228808] : perlquestion . print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi

Does anyone know if its possible to pass an array declared in one sub-routine to another sub-routine.
maybe like so:
&FOO(@array) from &BAR(@array)

Any ideas?

Replies are listed 'Best First'.
Re: Pass local array by reference?
by zakb (Pilgrim) on Jan 21, 2003 at 20:22 UTC

    Yes it is. Are you experiencing problems doing this? If so, please post at least a snippet of your code so we can try and help.

    Depending on the size of @array, you may want to pass it by reference. You do this by using \@array. You may want to look at perldoc perlreftut for more information.

Re: Pass local array by reference?
by Raziel (Initiate) on Jan 21, 2003 at 20:22 UTC
    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
      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.
Re: Pass local array by reference?
by Coruscate (Sexton) on Jan 21, 2003 at 21:30 UTC

    Maybe something like the following can help you... Untested:

    #!/usr/bin/perl -w use strict; sub foo { my $array = shift; print join(",", @{$array}), "\n"; } sub bar { my $array = shift; return reverse @{$array}; } my @array = ('foo', 'bar', 'qux'); my @bar = bar( \@array ); foo( \@bar );