How to pass a hash to a Perl routine?

In one of my main (or primary) routines, I have two or more hashes. I want the foo () routine to receive these possibly multiple hashes, like various hashes. Right now I have no preference if they go by value or as links. I have been struggling with this for the last few hours and will be grateful for the help, so I don't need to leave perl for php! (I use mod_perl or will)

I now have an 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 expand it so that in dumpvals I can do something like this:

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

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

How to do this in the last code snippet above?

+4
source share
2 answers

I believe this is what you are looking for:

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

    Keys
  • work on hashes, not hash links, so you need to dereference using %

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

+4
source

To 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"; } } } 

His conclusion, triggered in your question,

  12
 3: 4
 1: 7
 3: 8
 fifteen
 3: 6 
+3
source

Source: https://habr.com/ru/post/1305281/


All Articles