Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

How do I pass more than one array or hash to a subroutine

by vroom (His Eminence)
on Jan 18, 2000 at 23:10 UTC ( [id://2147]=perlquestion: print w/replies, xml ) Need Help??

vroom has asked for the wisdom of the Perl Monks concerning the following question: (subroutines)

How do I pass more than one array or hash to a subroutine

Originally posted as a Categorized Question.

  • Comment on How do I pass more than one array or hash to a subroutine

Replies are listed 'Best First'.
Re: How do I pass more than one array or hash to a subroutine
by hossman (Prior) on May 02, 2004 at 05:30 UTC

    If you declare your subroutine with a function prototype specifying each argument as \% or \@, then your method will automatically get a reference to the hashes/arrays passed to it, without the person calling the function/method/subroutine needing to do anything special.

    Note that, like all prototypes, this doesn't work when calling the subroutine using & or as a method.

    See the 'Prototypes' section of perlsub for more details, or this node for a good example.

Re: How do I pass more than one array or hash to a subroutine
by vroom (His Eminence) on Jan 18, 2000 at 23:10 UTC
    You need to pass these by reference, otherwise Perl will not see each array or hash as distinct.

    You can create a reference by simply prefixing a variable with \ like so:

    processarrays(\@array1, \@array2); processhashes(\%hash1, \%hash2);
    To use them inside of their routines you can do stuff like the following:
    $sub processarrays{ my($a1, $a2) = @_; foreach(@$a1){ # dereferences $a1 print $_; } for($i=0; $i<@$a2; $i++){ print $a2->[$i]; #get at a particular index within array } } sub processhashes{ my($h1,$h2)=@_; foreach my $key(keys %$h1){ #derefences $h1; print $h1->{$key}; #lookup based on $key } }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-18 18:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found