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

A 'permanent' keyword

Thread Next
From:
Ovid via perl5-porters
Date:
November 10, 2021 18:59
Subject:
A 'permanent' keyword
Message ID:
904718157.1560072.1636570743849@mail.yahoo.com
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 :)
Best,Ovid-- IT consulting, training, specializing in Perl, databases, and agile developmenthttp://www.allaroundtheworld.fr/. 
Buy my book! - http://bit.ly/beginning_perl
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