in reply to Re^2: 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

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

Replies are listed 'Best First'.
Re^4: Print hash keys and lookup ...
by Lotus1 (Vicar) on Feb 02, 2017 at 14:42 UTC

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