develooper Front page | perl.perl5.porters | Postings from November 2021

Re: A 'permanent' keyword

Thread Previous | Thread Next
From:
David Nicol
Date:
November 11, 2021 19:58
Subject:
Re: A 'permanent' keyword
Message ID:
CAFwScO9wn=TruihmmhhG7=XAcnn0S2Bd=621CaK-yW6Fy5P=tQ@mail.gmail.com
>
>     sub variables {
>         my $name = shift;
>
        return sub {
>             my $my = 1;
>             state $state = 1;
>             permanent $permanent = 1;
>             say "$name: my is $my. state is $state. permanent is
> $permanent";
>             $_++ for $my, $state, $permanent;
>         }
>     }
>


Lest we forget, "state" got introduced because "my $x if 0;" was turned
into a syntax error or something.
Here's how to produce the requested output using Perl 5.0:

{ # scope to hold $permanent
  my $permanent = 1; # gets declared at parse-time,
                     # but remains undef until execution reaches this line
                     # or the first time the result of variables is invoked
  sub variables {  # closes over $permanent
      my $name = shift;
      my $state = 1;
      sub { # closes over $name and $state
          my $my = 1; # goes away after getting incremented
          print "$name: my is $my. state is $state. permanent is
$permanent\n";
          $_++ for $my, $state, $permanent;
      }
  }
}



-- 
"Lay off that whiskey, and let that cocaine be!" -- Johnny Cash

Thread Previous | Thread Next


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