develooper Front page | perl.fwp | Postings from July 2003

Re: my if?

From:
fun_with_perl
Date:
July 1, 2003 10:02
Subject:
Re: my if?
Message ID:
bdsep8$38a$1@post.home.lunix
In article <200307011440.h61EeYbh017204@mail.rev.net>,
	"Bernie Cosell" <bernie@fantasyfarm.com> writes:
> On 1 Jul 2003 at 10:30, Ronald J Kimball wrote:
> 
>> On Tue, Jul 01, 2003 at 05:15:09PM +0300, Vladi Belperchinov-Shabanski wrote:
>> 
>> >   my $id = 1 if $_ == 3;
> 
>  [...]
> 
>> This was an accidental feature that is now kept for backwards
>> compatibility, because some programmers have used it to create static
>> variables.  It's best to avoid it, however.
> 
It's however not exactly the same as a static variable, 
It's one value per recursion level....

perl -wle '$m="static0"; 
sub fun { 
    my $a if 0; 
    $a||=++$m; $n = shift; 
    fun(0) if $n; 
    print $a 
} 
fun(5); 
fun(5)'

static2
static1
static2
static1

> It is undefined behavior [even though it works currently in every version 
> of Perl] and so it IS best to avoid it.  What I don't understand is why 
> the powers-that-be provide so much resistance to putting in a simple 
> 'static' declaration that would work the same way, only be defined-and-
> legal.  e.g.,:
>    sub x
>    {   static $vbl ;
>         [...]
> 
> Oh well, I guess re-opening that wound isn't much fun...

It doesn't really give you anything you don't already have by writing

{
    my $vbl;
    sub x {
    ....
    }
}



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About