Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Which way is recommended ?

by betterworld (Deacon)
on Nov 21, 2008 at 18:59 UTC ( #725208=note: print w/ replies, xml ) Need Help??


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.


Comment on Re: Which way is recommended ?
Select or Download Code
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

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://725208]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2014-08-22 11:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (156 votes), past polls