As @TedLyngmo points out in a comment to your OP, const state
is not valid Perl. const
is a pragma, so works at compile time, while state
is a runtime construct.
In terms of your efficiency requirement, that the GeoIP2::Database::Reader
constructor is called only once, either will work. If you further want it to be read-only so that you cannot inadvertently invalidate the reference, you can still use both. const
does it for you automatically, but you can duplicate that behavior with state
with a layer of indirection:
sub ip_cc_database {
state $db = GeoIP2::Database::Reader->new(file => '/etc/project/GeoLite2-Country.mmdb');
}
sub get_ip_country {
my ($ip_address) = @_;
my $ip_cc_database = ip_cc_database();
...
}
The answer to your question about when to use one over the other is a bit more nuanced.
The real difference between the two approaches is when the constructor is called. Using const
it's during the compile phase, with state
it's during runtime.
If you're application always calls get_ip_country
, and you don't care about amortizing startup costs over the lifetime of the process, const
is simpler.
However, if you don't always call get_ip_country
, and creating the GeoIP2::Database::Reader
object is expensive, then using state
means you only pay for that cost if you need it.
There's also the user experience to consider. If your program is interactive or if it starts generating output before you need to call get_ip_country
, delaying creating the object until its actually needed means your program doesn't just sit there seemingly doing nothing until all of the startup has completed.