Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
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 pondering the Monastery: (7)
As of 2015-07-31 06:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (274 votes), past polls