Hello,

I am seeing some unexpected behaviour when nesting a function inside another.

The inner function keeps seeing the old version of variables declared in the outer function.

For example:

#!/usr/bin/perl use strict; sub outer_function { my ($v1, $v2) = @_; print STDERR "Outer \$v1: " . \$v1 . " = $v1\n"; return inner_function($v1) . ", $v2"; sub inner_function { print STDERR "Inner \$v1: " . \$v1 . " = $v1\n"; return $v1; } } print "First call: " . outer_function("A", "B") . "\n"; print "Secnd call: " . outer_function("X", "Y") . "\n";

I was expecting the (standard) output to be:

First call: A, B Secnd call: X, Y

But instead I get:

Outer $v1: SCALAR(0xa0078a8) = A Inner $v1: SCALAR(0xa0078a8) = A First call: A, B Outer $v1: SCALAR(0x9fee760) = X Inner $v1: SCALAR(0xa0078a8) = A Secnd call: A, Y

Why does inner_function() keep seeing the old version of $v1 instead of the new one that outer_function() sees?

Is there any way to prevent this, and have inner_function() see the same address as outer_function() every time they are called?

Thanks in advance!

N

PS: Perl version is "v5.10.0 built for i486-linux-gnu-thread-multi" (Debian 5.0.6, perl 5.10.0-19lenny2)


In reply to Nested sub's beget undead variables? by Nivlem

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.