开发者

How can I pass a hash to a Perl subroutine?

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}); 

# creat开发者_StackOverflow社区e 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?


I believe this is what you're looking for:

sub dumpvals {
    foreach my $key (keys %{$_[0]}) {
        print "$key: $_[0]{$key}\n";
    }
}
  • An element of the argument array is a scalar, so you access it as $_[0] not @_[0].

  • keys operates on hashes, not hash refs, so you need to dereference, using %

  • And of course, the keys are scalars, not hashes, so you use my $key, not my %key.


To have dumpvals dump the contents of all hashes passed to it, use

sub dumpvals {
  foreach my $h (@_) {
    foreach my $k (keys %$h) {
      print "$k: $h->{$k}\n";
    }
  }
}

Its output when called as in your question is

1: 2
3: 4
1: 7
3: 8
1: 5
3: 6
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜