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.


All dogma is stupid.

Replies are listed 'Best First'.
Re^6: nested <FILE> read returns undefined?
by argv (Pilgrim) on Apr 01, 2006 at 18:43 UTC
    Your notes were spot-on. Mea Culpa on the $1 and $2 part.

    One caveat to your corrected code was another oversight on my part in my more brief explanation of the rationale for my code segment (which reminded me why I did it the way I did in the first place): each record "may" contain more than one "image: /path..." key-value pair, which is what requires reading ahead to the "----" line before returning to the outside control loop. Your version will just fine the next "image:" key, which would have been the right thing to do if it weren't for that condition.

    Anyway, all's well now.