How can I pass a hash to a Perl subroutine?

Posted by Vishalrix on Stack Overflow See other posts from Stack Overflow or by Vishalrix
Published on 2010-03-27T02:39:52Z Indexed on 2010/03/27 15:23 UTC
Read the original article Hit count: 184

Filed under:
|
|
|
|

In one of my main( or primary) routines,I have two or more hashes. I want the subroutine foo() to recieve these possibly-multiple hashes as distinct hashes. Right now I have no preference if they go by value, or as references. I am struggling with this for the last many hours and would appreciate help, so that I dont have to leave perl for php! ( I am using mod_perl, or will be)

Right now I have got some answer to my requirement, shown here

From http://forums.gentoo.org/viewtopic-t-803720-start-0.html

# sub: dump the hash values with the keys '1' and '3' 
sub dumpvals 
{ 
   foreach $h (@_) 
   { 
      print "1: $h->{1}   3: $h->{3}\n"; 
   } 
} 

# initialize an array of anonymous hash references 
@arr = ({1,2,3,4}, {1,7,3,8}); 

# create a new hash and add the reference to the array 
$t{1} = 5;
$t{3} = 6;
push @arr, \%t; 

# call the sub 
dumpvals(@arr);

I only want to extend it so that in dumpvals I could do something like this:

foreach my %k ( keys @_[0]) {
    # use $k and @_[0], and others
}

The syntax is wrong, but I suppose you can tell that I am trying to get the keys of the first hash ( hash1 or h1), and iterate over them.

How to do it in the latter code snippet above?

© Stack Overflow or respective owner

Related posts about perl

Related posts about references