Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: Which way is recommended ?

by betterworld (Curate)
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.

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

    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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://725208]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (6)
As of 2018-02-19 09:52 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (260 votes). Check out past polls.