And you've made debugging tricky by not providing code that clearly replicates your issue - neither Foo nor Bar are ever called or referenced, your global $gVar is never assigned a value and the flow of your program is unclear. Please read I know what I mean. Why don't you?.

Based on your comments, it looks like you expect to assign $gVar a value as a loop index and then maintain that value when Bar is called within the loop. However, when you use $gVar as the index on your foreach, you actually create a lexically scoped copy (or rather a local alias for the list element). When you then call Bar, it only sees the global. It's discussed (briefly) in Foreach Loops. Perhaps this example will provide clear flow:

my $var = 5; foreach $var (1 .. 3) { print $var; print_var(); } print $var; sub print_var {print $var};

Outputs: 1525355

Update: Cleaned up some unclear language.


In reply to Re: Tricky scope problem by kennethk
in thread Tricky scope problem by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.