in reply to foreach-loop-local var in sub
... strange, in your case I would expect to see a warning like "variables won't stay shared"...
These kind of problems are easily avoided by either using lexical subs:
use strict; use warnings; foreach (0, 1) { my $i = $_; my $print = sub { print $i; }; $print->(); # 0,1 }
or just not expecting to be able to easily redefine package subs at runtime, they are defined only once at compile time:
use strict; use warnings; my $i; sub my_print { print $i; }; foreach (0, 1) { $i = $_; my_print(); # 0,1 }
Anyway, while there are good use-cases for closures, I'd expect a beginner to go easy and pass arguments normally :
use strict; use warnings; sub my_print { my ($i)=@_; print $i; }; foreach (0, 1) { my_print($_); # 0,1 }
Cheers Rolf
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: foreach-loop-local var in sub
by NetWallah (Canon) on Jan 22, 2013 at 02:39 UTC | |
by LanX (Saint) on Jan 22, 2013 at 03:24 UTC | |
by Athanasius (Archbishop) on Jan 22, 2013 at 03:54 UTC | |
by LanX (Saint) on Jan 22, 2013 at 04:00 UTC |
In Section
Seekers of Perl Wisdom