in reply to subroutine reference parameters
#!/usr/bin/perl -w use warnings; sub printElement(\%$) { my $hash_ref = $_[0]; my $key = $_[1]; print $key." ".$hash_ref->{$key}."\n"; } my %hash = (0 => 'a', 1 => 'b', 2 => 'c'); while(($key) = each(%hash)) { printElement(%hash, $key); }
A large fraction of your problem can be traced back to incorrect use of Prototypes. For one thing, note that by using the & you are disabling the prototype. As well, if you hadn't disabled the prototype, passing in a hash reference would violate the prototype. In the end, your real problem is that using %hash in list context results in resetting the iterator in each. This is one of the reasons many people favor keys for the kind of loop you are describing.
As a side note, consider using strict: see Use strict warnings and diagnostics or die.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: subroutine reference parameters
by AnomalousMonk (Archbishop) on Jun 03, 2011 at 17:30 UTC |