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

Re: my if?

From:
Bernie Cosell
Date:
July 1, 2003 07:40
Subject:
Re: my if?
Message ID:
200307011440.h61EeYbf017204@mail.rev.net
On 1 Jul 2003 at 17:15, Vladi Belperchinov-Shabanski wrote:

> this one:
> 
> use strict;
> 
> for(1..3)
>   {
>   my $id = 1 if $_ == 3;
>   print "[$id]\n";
>   $id = 999;
>   }

This is just another instance of what I've posted about [on c.l.p.m] a 
few times, "cheap static variables".  Perl's mechanism for static 
variables is very elegant and very powerful, but is pretty syntactically 
ugly and generally is more than you want.  So if you just do:

   sub x
   {   my $staticvbl if 0 ;
        ....
   }

You now have a simple static variable -- the 'my' gets compiled at 
compile time, so you get a variable and 'use strict' is happy... BUT: 
since the 'my' isn't *executed* at run time, you end up with the effect 
of a static variable.

For example:
   sub x
   {   my $staticvbl if 0 ;
       $staticvbl += 1 ;
       print "$staticvbl\n" ;
   }
   x();
   x();
   x();

prints:
1
2
3

  /Bernie\

-- 
Bernie Cosell                     Fantasy Farm Fibers
mailto:bernie@fantasyfarm.com     Pearisburg, VA
    -->  Too many people, too few sheep  <--       






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