in reply to Re: Print hash keys and lookup the keys for values in another filr
in thread Print hash keys and lookup the keys for values in another filr

I didn't comment on this section before since the program seems to have had very little effort put into it. The last if !line; part will never do anything even if corrected since $line is only declared and assigned a value if the regex matches.

my $line = $_ if /\bWood\b/; chomp ($line); last if !line;

Perhaps something like last if /^\s*$/ placed ahead of the my $line = $_ ... would work.

Replies are listed 'Best First'.
Re^3: Print hash keys and lookup ...
by haukex (Archbishop) on Feb 02, 2017 at 12:43 UTC

    Hi Lotus1,

    The last if !line; part will never do anything even if corrected

    Turns out I missed it yesterday - the line does do something:

    $ perl -wMstrict -n my $line = $_ if /\bWood\b/; chomp ($line); print "BANG!\n" if !$line; __END__ Hello, Wood World Foobar

    Outputs:

    Use of uninitialized value $line in scalar chomp at - line 2, <> line +2. BANG!

    The ... if !$line gets triggerd when $line is false, which is a case that can happen.

    There's another thing I missed yesterday: my $line = $_ if /\bWood\b/;, to which perlsyn has to say this:

    NOTE: The behaviour of a my, state, or our modified with a statement modifier conditional or loop construct (for example, my $x if ...) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.

    So really, that entire loop body needs a rewrite, maybe:

    while (<$fh>) { chomp; next unless /\bWood\b/; ... }

    Regards,
    -- Hauke D

      Good points. Using my in a conditional statement is something I got burned by a while back and quit doing and forgot why.

Re^3: Print hash keys and lookup ... (updated)
by haukex (Archbishop) on Feb 01, 2017 at 17:00 UTC

    Hi Lotus1,

    The last if !line; part will never do anything even if corrected

    You're right of course, I was at that moment more focused on getting the code compiling, and there was lots more to explain, so I skipped the line that doesn't do anything :-) Update: Oops, the line does do something, see my other reply.

    Thanks,
    -- Hauke D