jerzy has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I have following code in script.pl(this is only part):
my $i = 'Insert'; $i->dodaj_narzut($products_price, \%zakresy)
There is following code in package "Insert.pm":
sub dodaj_narzut { my ($class,$cena,$zakresy) = @_; my $narzut = $class->ret_narzut($cena,$zakresy); my $new = sprintf('%.2f', $cena+($cena*($narzut/100))); return $class->zaokraglenie($new); } sub ret_narzut { my ($class,$cena,$zakresy) = @_; # use Data::Dumper; # print Dumper($zakresy); while (($zakres,$wartosc) = each %$zakresy) { my @zak = split '-', $zakres; if ($cena > $zak[0] and $cena <= $zak[1]) { return $wartosc; } } print "55\n"; return 55; }
The problem is that in subroutine "dodaj_narzut" half of the time it's like hash reference doesn't exist. It skips while loop. Next time when subroutine is executed it works perfectly - it goes through while loop and returns proper "$wartosc". But if I uncomment "Use Data::Dumper" and "print Dumper($zakresy)" while loop is executed every time. When I resign on using references it also works OK every time. It must be something with the references.

Thank you for any help.
Best regards,
Jerzy

Replies are listed 'Best First'.
Re: Half of hash references are missing
by ikegami (Patriarch) on May 11, 2011 at 19:16 UTC

    Each hash has only one iterator used by all each on that hash. You must have something like this:

    my %h = map { $_ => 1 } qw( a b c d ); while (my $k = each(%h)) { last; } while (my $k = each(%h)) { print("$k\n"); # a b d }

    Data::Dumper causes the iterator to be reset. keys(%h) will do that too.

    my %h = map { $_ => 1 } qw( a b c d ); while (my $k = each(%h)) { last; } keys(%h); while (my $k = each(%h)) { print("$k\n"); # c a b d }
      Thank you very much. This really worked.
      Best regards,
      Jerzy