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
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.