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

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 $_.

Replies are listed 'Best First'.
Re^4: "$_" vs. $_
by bsdz (Friar) on Apr 08, 2007 at 08:40 UTC
    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.