Perl: The unexpected behavior of $ _

use Modern::Perl; use DateTime; use autodie; my $dt; open my $fh, '<', 'data.txt'; # get the first date from the file while (<$fh> && !$dt) { if ( /^(\d+:\d+:\d+)/ ) { $dt = DateTime->new( ... ); } print; } 

I expected this loop to read every line of the file until the first datetime value is read.

Instead, $ _ is unified, and I get a message download of "uninitialized value of $ _ as pattern matching" (and print).

Any ideas why this is happening?

BUT

+7
source share
1 answer

$_ is only set if you use the while (<$fh>) form, which you are not.

Look at this:

 $ cat t.pl while (<$fh>) { } while (<$fh> && !$dt) { } $ perl -MO=Deparse t.pl while (defined($_ = <$fh>)) { (); } while (<$fh> and not $dt) { (); } t.pl syntax OK 

From perlop docs:

Usually you should assign the return value to a variable, but there is one situation where automatic assignment occurs. If and only if the input character is the only thing inside the conditional while statement (even if it is disguised as a for (;;) loop), the value is automatically assigned to the global variable $ _, destroying everything that was previously.

+20
source

All Articles