Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2016-08-27 15:12 GMT
Find Nodes?
    Voting Booth?
    The best thing I ever won in a lottery was:

    Results (380 votes). Check out past polls.