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

Re: A 'permanent' keyword

Thread Previous | Thread Next
From:
Branislav ZahradnĂ­k
Date:
November 11, 2021 09:59
Subject:
Re: A 'permanent' keyword
Message ID:
CAB=rbO=JH6n=bYepNUdoFO8BxWc29ptLAUkwcVw=YzEphDhFpA@mail.gmail.com
On Wed, 10 Nov 2021 at 19:59, Ovid via perl5-porters <perl5-porters@perl.org>
wrote:

> Hi Porters!
>
> I would love to see a permanent keyword for Perl. It initializes a
> variable once and only once. It would look like this:
>
>     #!/usr/bin/env perl
>
>     use 5.38.0;
>     use warnings;
>
>     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;
>         }
>     }
>
>
you can achieve described behaviour by moving "permanent line" into parent
scope:

sub variables {
   my $name = shift;
  state $permanent = 1;
  return sub {
    my $my = 1;
    state $state = 1;
    say "$name: my is $my. state is $state. permanent is $permanent";
    $_++ for $my, $state, $permanent;
  }
}

Extrapolating your idea - it will be imho better to be able to specify
variable "in scope", eg:
sub variables {
   SCOPE:
   my $name;
   return sub {
     state $state;
    # expressing intention not suggesting syntax
     UPPER SCOPE { state $permanent }
  }
}

it will allow to concise for example phaser blocks, current state:
my $foo;
BEGIN { $foo = 'bar' };

BEGIN { UPPER { my $foo = 'bar' } }

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