Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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.


Comment on Re: passing arrays to subroutines
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2014-10-02 03:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (48 votes), past polls