Peter Daum wrote:
Hi,

Hello,

I just got bitten by a very simple issue, where Perl behaves totally
different from what I had expected;

According to the documentation, lexical variables are visible only after
the line they have been declared in; they may be initialized;
otherwise their value is undefined, so the following short code snippet:

foreach (qw(a b c)) {
    my $t;
    warn("\$t == ", $t||'undef', "\n");
    $t=$_;
}

will 3 times print "$t == undef" (as to be expected).
Now a minor variation:

my $x=undef;
foreach (qw(a b c)) {
    my $t =$x if $x;
    warn("\$t == ", $t||'undef', "\n");
    $t=$_;
}

$t would be initialized with the value of $x if that was true;
otherwise (at least that's what I would expect) $t should be undefined,
so the result would be as before. The real outcome, however, is:

$t == undef
$t == a
$t == b

$t now retains its value from the last loop iteration.
Is this a bug or a feature (tm)?
If it is a feature, then why isn't the value also retained in the 1st example?

perldoc perlsyn
[ SNIP ]
    NOTE: The behaviour of a "my" statement modified with a statement
    modifier conditional or loop construct (e.g. "my $x if ...") is
    undefined.  The value of the "my" variable may be "undef", any
    previously assigned value, or possibly anything else.  Don’t rely on
    it.  Future versions of perl might do something different from the
    version of perl you try it out on.  Here be dragons.


John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.                            -- Larry Wall


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to