Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^4: Lost anonymous subs

by kappa (Chaplain)
on Dec 10, 2004 at 12:07 UTC ( [id://413814]=note: print w/replies, xml ) Need Help??


in reply to Re^3: Lost anonymous subs
in thread Lost anonymous subs

my @abc; for my $m qw/a b c/ { push @abc, sub { $m }; } print $_->() . "\n" for @abc;
No assignments and still, those subs each has its own $m. Or does the for my $m creates a new variable on each iteration?
--kap

Replies are listed 'Best First'.
Re^5: Lost anonymous subs
by diotalevi (Canon) on Dec 10, 2004 at 15:02 UTC

    The my() operator has a runtime effect of creating a new variable so each time you start that loop, you have a new variable to have potentially bound to. This also works if you write code like this.

    my @abc; for my $m ( qw/a b c/ ) { push @abc, \ $m; } print @abc
      I may sound annoying but what about this? The my is executed only once.
      my (@abc, $m); for $m ( qw/a b c/ ) { push @abc, \ $m; } print "$$_\n" for @abc;
      --kap

        Well... this gets into a feature of for() and stops being about my(). for is special in that it aliases the "a", "b", and "c" variables over $m during the loop so even though you didn't say for my the effect is the same. So there's a sort of implicit my() happening there anyway. What you'll notice though, is that if you used strict, the implicit my() won't take care of making sure that variable is declared so you'd still have an error unless you said it as for my or if the loop variable already existed outside the loop.

        At this point, however, you may just want to start reading the output of things like Devel::Peek::Dump, perl -MO=Concise your_script.pl, and reading pp_enteriter in pp_ctl.c.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-03-28 17:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found