Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^2: "$_" vs. $_

by mrpeabody (Friar)
on Apr 09, 2007 at 03:25 UTC ( [id://608927]=note: print w/replies, xml ) Need Help??


in reply to Re: "$_" vs. $_
in thread "$_" vs. $_

So I would say that any code that *sets* $_ is, by definition, wrong.
Unnecessary, perhaps, but not wrong. Setting $_ can be useful:
  1. As a topicalizer in a single-item for loop, to make a series of operations on a common value read more cleanly.

    Instead of this:

    $h->{foo}{bar} =~ s/[._]/ /g; Some::Custom::Function($h->{foo}{bar}); $h->{foo}{bar} =~ s/^\s+//; $h->{foo}{bar} =~ s/\s+$//; $h->{foo}{bar} =~ s/`/'/g;
    You can write this:
    for ($h->{foo}{bar}) { s/[._]/ /g; Some::Custom::Function($_); s/^\s+//; s/\s+$//; s/`/'/g; };

  2. And the occasional weird circumstance, like conveniently modifying the values of a hash:
    map { $_ = foo( $bar, $_ ) } values %somehash;
On the other hand, where real for loops are concerned, I find it reduces confusion to always provide your own lexical topic (e.g.  for my $key (@keys) { ... } ). A bit backwards from the way the language is designed, I suppose.

Replies are listed 'Best First'.
Re^3: "$_" vs. $_
by Beechbone (Friar) on Apr 10, 2007 at 14:31 UTC
    Um, in both examples you are not setting $_---you are only modifying it.

    Small difference, but with it, I'd also say "never set $_".


    Search, Ask, Know
      Um, in both examples you are not setting $_---you are only modifying it.
      Interesting distinction. I think of them as synonyms, and would certainly argue that any statement that starts with "$_ =" is "setting" the variable. However, what name we use when giving a variable a new value is not really the point.

      What makes both of these examples useful is that they implicitly alias $_ to another variable before acting on it. That's where they differ from the OP's usage.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-04-20 03:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found