On Jan 13, 2008 6:22 AM, Peter Daum <[EMAIL PROTECTED]> wrote:
snip
>     my $t =$x if $x;
snip
> $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?
snip

People argue about whether this is a bug or not*.  In my opinion, it
is a bug because the variable's scope should be within the if
statement.  You wouldn't expect to be able the use the variable if the
code looked like this

if ($x) {
    my $t = $x;
}
print "$t\n";

so why should you be able to use it because it has been changed to this

my  $t = $x if $x;
print "$t\n";

The proper way to get static variables prior to Perl 5.10 is

{
    my $counter;
    sub inc {
        return $counter++;
    }
}

With Perl 5.10 we can use state** instead of my:

sub inc {
    state $counter;
    return $counter++;
}

* http://www.perlmonks.org/?node_id=95940
** http://perldoc.perl.org/functions/state.html

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


Reply via email to