Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

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

by bsdz (Friar)
on Apr 08, 2007 at 06:59 UTC ( [id://608880]=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.

I feel this is not a Golden rule. Setting $_ has its uses, especially when one would like to do regex operations not wishing to declare intermediate variables. It is generally wise to localise $_ before setting it. A good example of this kind of usage can be found here.

Replies are listed 'Best First'.
Re^3: "$_" vs. $_
by ikegami (Patriarch) on Apr 08, 2007 at 07:24 UTC

    In the so-called good example, both local $_ could easily have been replaced with my. You gain the readability of a named variable at the tiny cost of having to specify the topic of two operations.

    my @a = map { s/\s*(#.*)?$//g; $_ } <DATA>; my @b; while (my $group = shift @a) { if ($group =~ m/\D(\d+)-(\d+)(?:\D|$)/) { my $range = "$1-$2"; foreach my $i ($1..$2) { (my $addr = $group) =~ s/(\D)$range(\D|$)/$1$i$2/; push @a, $addr; } } else { push @b, $group; } } print join("\n", @b);

    There are cases where using $_ helps, but I don't think this is one of them.

    Note: The localization of $1 and $2 is unnecessary. It's already being done by the for.

    Note: local $_ doesn't preserve $_ in all situations, unfortunately. for ($var) is a far better way of aliasing $_.

      Thank you for your point regarding unnecessary localization of $1 and $2. Still, my point was avoiding intermediate (possibly unnecessary?) variables, i.e. $addr and $group in your code that incredibly looks very much like my original!

      Ultimately, I guess it is style. One thing I love about Perl is TIMTOWTDI and I admit I tend to go for minimal keyboard presses unless extra performance is needed. Then, I would probably lean to doing it in C++.

      Update: Incidentally, the named approach is probably a little faster than a localised one. However, only slightly!

        Still, my point was avoiding intermediate (possibly unnecessary?) variables,

        I did not add any new variables. You used two (both named $_) and so did I. My point was that naming two variables $_ is more confusing, less readable and less maintainable.

    A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (4)
As of 2024-04-24 12:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found