perlreadonly-variable

What is the difference between `state` and `const`?


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');
    ...
}

UPD
At this sub I do not change pointer togeoip database, so it should be const. But I not want recreate object each time when sub is called (this is slow). So I suppose it will be faster to use state, despite pointer is not changed.

It seems it should be const state $ip_cc_database


Solution

  • They do not do the same thing.