in reply to File Reading and Hash Accessing that isn't doing what you'd expect.

It seems to be related to the hash table, yet you don't show us the table.

Anyway, one problem with your code is that you iterate over a hash, abort in the middle and don't reset the iterator.

Iterating over a hash is a bad idea anyway - just store it the other way round (ie turn the values into keys and the other way round), and do a lookup:

# assuming you have no duplicate values: my %mapkey = reverse %keymap; sub findCharacterAsKey { my $loebnerLetter = shift; if (exists $mapkey{$lobnerLetter}) { return $mapkey{$lobnerLetter}; } else { warn "Could not resolve '$loebnerLetter'"; } }

Since you have to do the inversion of the hash only once, it'll be much faster and correct this way.

Perl 6 - links to (nearly) everything that is Perl 6.
  • Comment on Re: File Reading and Hash Accessing that isn't doing what you'd expect.
  • Download Code

Replies are listed 'Best First'.
Re^2: File Reading and Hash Accessing that isn't doing what you'd expect.
by Chris_Stevens (Initiate) on Jun 01, 2010 at 14:32 UTC

    Many thanks to everyone here!

    I didn't realise reversing a hashtable was simply a matter of using reverse, that will hopefully solve all my problems. Additionally I didn't know that iterators needed to be reset (oops).

    I know I was using it incorrectly (goes to show that trying to hack your way around causes unforeseen problems), just didnt know how to turn the hash around without having to re-edit it again since its a hard-coded map.

    Thanks a lot guys, will see if this helps.

      perlfaq4 might also be relevant for you. The start "just" talks about numbers, but later on section on hashes might really help you.