Home > Net >  What is the difference between `state` and `const`?
What is the difference between `state` and `const`?

Time:01-24

It seems similar to write:

use Const::Fast;
const $xx, 77;
sub test {
    do_something_with( $xx );    
}

or

sub test {
    state $xx =  77;
    do_something_with( $xx );    
}

What is the better way to accomplish this: via const or via state?

sub get_ip_country {
    my ($ip_address) = @_;
    my $ip_cc_database = GeoIP2::Database::Reader->new(file => '/etc/project/GeoLite2-Country.mmdb');
    ...
}

CodePudding user response:

They do not do the same thing.

  • state declares a variable that will only be initialized the first time you enter the function. It's mutable though, so you can change its value, but it will keep the value between calls to the same function. This program would for example print 78 and 79:
    sub test {
        state $xx = 77;     # initialization only happens once
        print   $xx . "\n"; # step the current value and print it
    }
    test; # 78
    test; # 79
    
  • const declares an immutable (readonly) variable that, if declared in a function, would be reinitialized every time the function is called.

CodePudding user response:

If you want a value that is constant, then you should use something like Const::Fast.

But if you want a value that can be changed, but which retains its value between calls to a function, then you need a state variable.

So running, this:

sub test {
  state $x = 1;

  say $x  ;
}

test() for 1 .. 10;

Gives this:

1
2
3
4
5
6
7
8
9
10

But running this:

use Const::Fast;

sub test {
  const my $x, 1;

  say $x  ;
}

test() for 1 .. 10;

Gives a runtime error:

Modification of a read-only value attempted at const_test line 12.
  •  Tags:  
  • Related