Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

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]
[Your Mother]: Please don't fight, mom and dad!
[erix]: friction gives warmth!
LanX comes back ...
[LanX]: FIGHT?
LanX orders pop corn
[erix]: ha ha, you missed it

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2018-03-19 21:24 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (246 votes). Check out past polls.