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 blue_cowdawg (Monsignor)
on Jan 21, 2013 at 15:55 UTC ( #1014474=note: print w/ replies, xml ) Need Help??


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


Comment on Re: foreach-loop-local var in sub
Select or Download Code
Re^2: foreach-loop-local var in sub
by choroba (Abbot) 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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (11)
As of 2014-12-19 13:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (82 votes), past polls