http://www.perlmonks.org?node_id=725208


in reply to Which way is recommended ?

instead of directly using $_

The term "directly" is not quite correct here, because it suggests that $_ is used in any case.

$_ will not be set if you write while( my $line = <$lfh> ).

In my opinion, using $_ is not really elegant. It's a global variable and it will be visible to called subroutines even if you localize it. Well, in perl 5.10 you can avoid this my using my $_. But unlike with named variables, you won't get any errors from strict if you forget to my the variable.

Replies are listed 'Best First'.
Re^2: Which way is recommended ?
by DStaal (Chaplain) on Nov 21, 2008 at 20:42 UTC

    Also, a good part of Perl's operators and functions will modify $_ in some way. Even if you don't use it, a function you call might, and it'll get changed. This leads to hard-to-debug code of the worst kind...

    Reserve use of $_ to shell one-liners and map/grep blocks. The rest of the time assign your own variable.

Re^2: Which way is recommended ?
by matrixmadhan (Beadle) on Nov 21, 2008 at 19:15 UTC
    Thanks

    I should not have used the term 'directly' which means in any case with respect to $_; but that's not how it works.

    Too impressive. :)

      There is an implicit check for definedness when you do while (<FOO>) { }. See the perlop section on I/O Operators.

      while (<FOO>) { # do stuff } # terminates if we get a line that evaluates to false. while (my $l = <FOO>) { # do stuff } # only terminates at end of file (or error reading file) while (defined(my $l = <FOO>)) { # do stuff } # Let's take advantage of $_ and be somewhat safe(r). { local $_; while (<FOO>) { # do stuff } }


      TGI says moo