in reply to Re^4: nested <FILE> read returns undefined?
in thread nested <FILE> read returns undefined?
Thanks for taking the time to explain this. First, there's a bug in your code, because $1 and $2 will not be reset when the while loop starts over, but retain their old values, despite the fact that the match did not succeed (see the warning about this in perldoc perlre). So the line
next if !$key || !$value;will not skip lines that don't contain a key-value pair.
Here's how I would write this, without using the inner while loop:
my $curimage; while (my $line = <DATA>) { $line =~ /^([^:]*): (.*?)$/m or next; my ($key, $value) = (lc $1, $2); $curimage = $value if ($key eq "image"); next if(!exists $db->{$curimage}); # ..process key-value pairs }
This has the obvious disadvantage that you need to look up $db more often, so if $db is not just a hash reference and lookups are more expensive this will be slow. But you can get around that by memoizing $db->{$curimage} and I think the code is clearer this way. YMMV of course.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: nested <FILE> read returns undefined?
by argv (Pilgrim) on Apr 01, 2006 at 18:43 UTC |