On Wed, Nov 10, 2021 at 7: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 :) > Ultimately, state is equivalent to "a my variable outside the current sub" and permanent is equivalent to "a my outside the outermost sub" (or a state inside the outermost sub). They're both useful concepts, but they can also both already be expressed in the traditional ways. I'm not sure permanent would be common enough to warrant its own keyword, but probably we need to make this distinction clearer in the docs. LeonThread Previous | Thread Next