in reply to Passing hashes to subs?

You can use

&callsub(%hashtopass); sub callsub { %hashread = @_; foreach $k (keys %hashread) { print "$k => $hashread{$k}\n"; } }

but I prefer to use references:

&callsub(\%hashtopass, $otherStuff); sub callsub { my ($hashref, $otherParam) = @_; # or: my $hashref = shift; if you prefer that foreach my $k (keys %{$hashref}) { print "$k => $hashref->{$k}\n"; } }

This way, you can even pass along other parameters.

Replies are listed 'Best First'.
Re: Re: Passing hashes to subs?
by Chady (Priest) on Aug 01, 2002 at 12:33 UTC
    &callsub(%hashtopass); sub callsub { %hashread = @_;

    I don't think this is good practice.. what if you decide to pass a scalar along with that and forgot to shift it out before assigning the list to the hash? you might end up with a corrupted list, or worst, a legitimate list with wrong values shooting yourself in the foot.


    He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

    Chady | http://chady.net/

      Yes, that's why I suggested the second approach using references. But I neglected to point out the dangers to the original poster. Thanks!

      FWIW, I do like to use it if (and only if...) the function is designed to receive only named parameters. E. g.

      sub create { my $self = shift; my %p = @_; print "$p{color} p{animal}" for (1..$p{count}); } $zoo->create(animal => 'camel', count => '10', color => 'green');

      One could opt to create the zoo using a hash reference as in

      $zoo->create({animal => 'monkey', ...});

      but I guess that is a matter of style.