Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re: passing arrays to subroutines

by perlfan (Curate)
on Mar 16, 2005 at 14:47 UTC ( #439959=note: print w/replies, xml ) Need Help??

in reply to passing arrays to subroutines

Pass by reference - this is what I usually do:
my @array = qw(a b c d e f); my @new_array = do_something(\@array); #<- note the "\" sub do_something { my $array_ref = shift; my @new = (); foreach (@{$array_ref}) { #<- treat the ref as an array # do some stuff like build @new } return @new; }
You can also return ref's which means you can return mulitiple array, hash, and scalar references by using as a list with out them getting all flattened out together.

To give you a visual of what an array looks like versus an array reference, Data::Dumper would show:

For '@array' outside the subroutine:
$VAR1 = a $VAR2 = b ..etc
For '$array_ref' inside the subroutine:
$VAR1 = [a,b,c,d,e,f]
This is because $array_ref points to an anonymous array passed to to the subroutine while @array IS the array.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://439959]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2017-11-25 08:47 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (355 votes). Check out past polls.