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

Re: foreach-loop-local var in sub

by tobyink (Abbot)
on Jan 21, 2013 at 16:06 UTC ( #1014478=note: print w/ replies, xml ) Need Help??


in reply to foreach-loop-local var in sub

sub definitions within control structures don't really work how you want them to work. Your my_print function only gets defined once; not each time around the loop. If you want to redefine the sub each time around the loop, use an anonymous sub (a.k.a. closure; coderef) - which can be given a name by assigning it to a glob.

This works:

use strict; use warnings; no warnings 'redefine'; # stub to declare sub name, allowing it to be used # as a bareword later on sub my_print (); foreach my $i (0, 1) { *my_print = sub () { print "[$i]\n"; }; my_print; }
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name


Comment on Re: foreach-loop-local var in sub
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (9)
As of 2014-07-30 03:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (229 votes), past polls