in reply to passing hash refs

You have been bitten by omitting use strict;use warnings. Specifically, on line 8 you say "scalar @{$hash_ref{$key}}" which is trying to access a non-existent hash named %hash_ref instead of a scalar named $hash_ref. You require the dereference operator to get that result; see perlreftut. You do the same on line 9.

Adding strictures and fixing that mistake gives:

#!/usr/bin/perl use strict; use warnings; my $hash_ref = set_up(); foreach my $key (keys %{$hash_ref}) { my $val = $$hash_ref{$key}; if (ref($val)) { print "\ntotal \'$key\' = ", scalar @{$hash_ref->{$key}}, "\n"; foreach my $act (@{$hash_ref->{$key}}) { print "\t$act\n"; } } else { print "$key - $val\n"; } } sub set_up { my (%hash,@array); @array=("feed","walk","pet","groom"); $hash{'one'}="cat"; $hash{'two'}="dog"; push(@{$hash{'actions'}},@array); return(\%hash); }

Replies are listed 'Best First'.
Re^2: passing hash refs
by fredsnertz (Initiate) on Apr 08, 2009 at 15:58 UTC
    Thank you so much for getting me an answer in 15 minutes to something I'd already spent hours on. You have inspired me to start using strict and warnings ... well my code is around 600 lines already and I should be able to wrap it up now ... I'll use those on my next project.
      I'll use those on my next project.

      Please reconsider. Use them now!

      Your maintenance challenges down the road will be much fewer AND simpler if you deal with the problems strict and warnings complain about now, while you still remember what your code means...

      (You should also add documentation and tests, seriously. But making things strict/warnings clean is a good start)


      Mike

      Bzzzt - wrong answer. Add strictures now. You've already seen the benefit - two errors detected in about 30 lines of code, so there could be about 38 more errors to find in the remaining 570 lines which is about another two weeks of possible debugging time saved! ;)


      True laziness is hard work