in reply to Printing only the "keys that have a value" in hash

an alternative to "exists" would be to undef all the empty hash keys, just prior to your main processing loop, if that suits.
also looks like your code has outgrown the hard-coded assignment in the hash...so refactoring appropriately would get rid of the need to use "exists".
the hardest line to type correctly is: stty erase ^H
  • Comment on Re: Printing only the "keys that have a value" in hash

Replies are listed 'Best First'.
Re^2: Printing only the "keys that have a value" in hash
by iphone (Beadle) on Nov 01, 2010 at 02:14 UTC

    I am sorry,I have no idea on what you are saying?

      just before your main processing instructions
      foreach $key(%my_hash) { delete $my_hash{"$key"} if(!exists($my_hash{"$key"})); }
      that will get rid of empty keys--assuming you're not interested in these--and henceforth you can now iterate over keys of the hash.
      the hardest line to type correctly is: stty erase ^H
        Unless I'm mistaken, this code won't do anything at all. You're getting each $key directly from the hash, so it's always going to exist. Perhaps you meant if (!defined $my_hash{$key})?

        Anyway, checking for defined-ness won't matter either since the "undefined" values are actually empty array refs, which are defined.

        #print Dumper( \%Hash_filematches ); -->Shows correct data

        But with the below code,the output is shown below

        print "PRINTING MATCHED HASHES\n"; foreach my $key ( keys %Hash_filematches ) { delete $Hash_filematches{"$key"} if(!exists($Hash_filematches{"$ke +y"})); my $value = $Hash_filematches{$key}; print "$key => $value\n" ; }

        This below is the output.It's still printing the array references as values and also the hash keys without values.

        PRINTING MATCHED HASHES array.xml => ARRAY(0x1b26ac8) file.xml => ARRAY(0x1b26af8) data.xml=> ARRAY(0x1b26ae0) multimedia.xml => ARRAY(0x1b26b58 ...... ......