Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Thoughts on the magicality of @_ and $_

by jarich (Curate)
on Jul 01, 2002 at 04:17 UTC ( [id://178464]=note: print w/replies, xml ) Need Help??


in reply to Thoughts on the magicality of @_ and $_

I used to always get bitten by this one:
use strict; my $name; foreach $name (qw/alfred benjamin casey donald eugene/) { print "$name\n"; } print "*$name*\n";
Of course this is simplified, but doesn't it seem like $name should be equal to "eugene" after the loop? But it isn't. It's undefined, because it was undefined at the start of the loop. So if you want to do something with the elements of the array and end up storing the last one as a side effect you have to do it in a similar way to this:
use strict; my $name; foreach my $loopname (qw/alfred benjamin casey donald eugene/) { $name = $loopname; print "$name\n"; } print "*$name*\n";
Which has never seemed as DWIMish as I wished for.

;)

jarich

Replies are listed 'Best First'.
Re^2: Thoughts on the magicality of @_ and $_
by Aristotle (Chancellor) on Jul 01, 2002 at 14:17 UTC
    I prefer it this way - in more traditional languages, I've actually been bitten by the existance of this side effect (or the desire to to use it cleverly). Not having this side effect may seem more awkward, but IMHO makes the code less kludgy and hackish.

    Makeshifts last the longest.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (10)
As of 2024-04-23 08:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found