|
Posted by smallpond on January 24, 2008, 12:58 pm
Please log in for more thread options
> As a matter of style and expectation, I'm wondering about relying on $_.
> Often, just for convenience I'll do a no-var foreach. For example:
> foreach (sort keys %SOMEHASH)
> { print "Processing $_\n" ;
> my $target = $SOMEHASH ;
> ....
> }
> and I'll refer to $_ here and there in the loop [e.g., if something fails
> I'll typically just do a 'die "Error processing $_: $!\n" ;' or the like].
> Is that bad form? I just sorted out a minor problem where I was calling an
> object method and I was surprised to discover that $_ was clobbered when I
> got back from the method.
>
> Is this a bug [even if a minor one] in the package? If not, what are the
> rules for when you should and shouldn't expect $_ to get messed up?
>
It is almost never a good idea to use $_ (or $a or $b) as
the loop variable in a foreach. see perltrap and perlvar.
"my $key" is quite reasonably priced and doesn't
get clobbered by subs that you call.
The rule is pretty simple: there's only one $_ in your
package, and there are many functions that use it implicitly.
Many subs should have local $_ but don't, so it is never good
to assume it will be preserved across a call.
The other thing to remember about foreach is that it creates an
alias for the value, not a copy.
|