http://www.perlmonks.org?node_id=1014504


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