Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: passing arrays to subroutines

by perlfan (Vicar)
on Mar 16, 2005 at 14:47 UTC ( [id://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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://439959]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-03-29 13:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found