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


in reply to foreach-loop-local var in sub

First off you've declared the sub as having no arguments. Secondly within the curly braces of the sub you have changed context and $i is uninitialized within that context and therefor you are going to print zeros for each iteration.

Here is code that does what you think it should:

foreach (0, 1) { my $i = $_; sub my_print { my $i = shift; print $i; } my_print( $i); }

Now... you could have saved yourself a lot of pain if you had

use strict; use warnings;
at the beginning of your code. Bailiff, lock him up.


Peter L. Berghold -- Unix Professional
Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

Replies are listed 'Best First'.
Re^2: foreach-loop-local var in sub
by choroba (Cardinal) on Jan 21, 2013 at 15:58 UTC
    you have changed context and $i is uninitialized within that context and therefor you are going to print zeros
    Not exactly true. Try with
    foreach (qw(a b)) {
    Update: Do not use numbers for testing behaviour, see Re^3: variable declaration question.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
          Not exactly true. Try with

      Eh? What do you mean by that? Trying the OPs code with your mod still gives the result that they are not after.


      Peter L. Berghold -- Unix Professional
      Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg