Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: while(<>) { ... } considered harmful

by BrowserUk (Pope)
on Sep 08, 2002 at 00:36 UTC ( #195944=note: print w/ replies, xml ) Need Help??


in reply to while(<>) { ... } considered harmful

'scuse my ignorance of nether regions below Perl's skirts, but would it impose a huge performance penalty for map and grep to localise $_ on entry?

I visualise them as subs with their own local scope. Would a local $_; at the top cost so very much?


Well It's better than the Abottoire, but Yorkshire!


Comment on Re: while(<>) { ... } considered harmful
Download Code
Re: Re: while(<>) { ... } considered harmful
by Ovid (Cardinal) on Sep 08, 2002 at 00:58 UTC

    Unless I totally misunderstood the above comments -- which is possible as I just briefly skimmed them -- the problem here is not that map and grep don't localize $_, but that they may execute code that may alter the value of $_, which in this case is aliased to a constant. Consider this code:

    $_ = 'Ovid'; %hash = map { $_ => 1 } qw/ foo bar baz /; print;

    That code will print 'Ovid' because $_ has been localized within the map statement. Now, if you try to alter the $_, your code fails because you're trying to alter a constant:

    $_ = 'Ovid'; %hash = map { $_ .= 'asdf'; $_ => 1 } qw/ foo bar baz /; print;

    To get around that, you can do this:

    $_ = 'Ovid'; %hash = map { local $_ = $_; $_ .= 'asdf'; $_ => 1 } qw/ foo bar baz /; print;

    That allows you to assign the aliased constant to a real variable, thus avoiding the problems outlined in this thread.

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2014-07-26 15:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (178 votes), past polls