Eug*_*kov -1 perl readonly-variable
看起来类似这样写:
use Const::Fast;
const $xx, 77;
sub test {
do_something_with( $xx );
}
Run Code Online (Sandbox Code Playgroud)
或者
sub test {
state $xx = 77;
do_something_with( $xx );
}
Run Code Online (Sandbox Code Playgroud)
实现此目的的更好方法是什么:viaconst或via state?
sub get_ip_country {
my ($ip_address) = @_;
my $ip_cc_database = GeoIP2::Database::Reader->new(file => '/etc/project/GeoLite2-Country.mmdb');
...
}
Run Code Online (Sandbox Code Playgroud)
UPD
在这个子我没有更改指向geoip数据库的指针,所以它应该是const。但我不想每次调用 sub 时都重新创建对象(这很慢)。所以我想尽管指针没有改变,但使用起来会更快state。
看来应该是const state $ip_cc_database
他们不做同样的事情。
state声明一个变量,该变量仅在您第一次进入函数时初始化。虽然它是可变的,所以您可以更改它的值,但它会在调用同一函数之间保留该值。例如,该程序将打印78并79:
sub test {
state $xx = 77; # initialization only happens once
print ++$xx . "\n"; # step the current value and print it
}
test; # 78
test; # 79
Run Code Online (Sandbox Code Playgroud)
const声明一个不可变(只读)变量,如果在函数中声明该变量,则每次调用该函数时都会重新初始化该变量。