in reply to subroutine reference parameters

You have a number of errors interacting to result in your bug. The closest code to that you posted that functions is:

#!/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
    In the end, your real problem is that using  %hash in list context results in resetting the iterator in each.

    Or dereferencing a reference to  %hash in list context. E.g.:

    >perl -wMstrict -le "my %hash = qw(a 1 b 2 c 3); my $hashref = \%hash; ;; for (1 .. 3) { my ($k) = each %$hashref; print qq{'$k' => '$hashref->{$k}'}; my @ra = %$hashref; } " 'c' => '3' 'c' => '3' 'c' => '3'

    Comment out the
        my @ra = %$hashref;
    statement for more-expected behavior.