Grrrrr

Mar 09, 2009 13:33

Find the bug.

#!/usr/local/bin/perl -w

use strict;

my %mappings = ("a" => "i am an apple",
"b" => "i am a banana");

sub findMapping {
my ($input) = @_;
while (my ($code, $fruit) = each(%mappings)) {
if ($input =~ /^$code/) {
return $fruit;
}
}
die("could not find a fruit for $input");
}

print findMapping("arthur");
print findMapping("andy");
print findMapping("alice");

And if you run it, you get:

$ perl ~/bin/testex.pl
could not find a fruit for andy at /home/neilk/bin/testex.pl line 15.
i am an apple



The each() iterator is not reset. Believe it or not, due to the early return, the next call will pick up in the middle of the last iteration. Sooner or later the iterator will fail to match and fall through to the die().

I feel like there used to be a way to fix this, but I can't find it in the current docs. It's not reset(). The only docs I've seen say to do a useless call keys to reset the iterator. This seems silly, and you might as well do that as a foreach over keys anyway then.
Previous post Next post
Up