On Wed, Nov 10, 2021 at 1:59 PM 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; > } > } > > my $first = variables('first'); > my $second = variables('name'); > > say "First"; > $first->(); > $first->(); > $first->(); > > say "Second"; > $second->(); > $second->(); > $second->(); > > And the output would be: > > First > first: my is 1. state is 1. permanent is 1 > first: my is 1. state is 2. permanent is 2 > first: my is 1. state is 3. permanent is 3 > Second > name: my is 1. state is 1. permanent is 4 > name: my is 1. state is 2. permanent is 5 > name: my is 1. state is 3. permanent is 6 > > > Currently, state's documentation says this: > > "state" declares a lexically scoped variable, > just like "my". However, those variables will > never be reinitialized, contrary to lexical > variables that are reinitialized each time their > enclosing block is entered. See "Persistent > Private Variables" in perlsub for details. > > But that's not quite correct. It's never reinitialized unless the scope is > dynamic, in which case it is. > > Permanent variables would *never* be reinitialized. Not only will this be > more clear to existing Perl developers, it might help new Perl developers > who misuse state variables. It might also clear up future issues with > Corinna, but I won't go there now :) > This is a bit confusing. The scope you created is not any more dynamic than any other - you are creating a different subroutine with its own pad. I think if you want a variable to be permanent through multiple pads, that's what the package stash is for. -DanThread Previous | Thread Next