当我使用严格时,我得到以下编译问题,否则它工作正常。我试图将“my”关键字用于属性,但这并不是在修复它。我做错了什么?
#Read properties file
open( F, 'properties' )
or die "properties file is missing in current directory. Error: $!\n";
while (<F>) {
next if (/^\#/);
(my $name, my $val ) = m/(\w+)\s*=(.+)/;
my $properties{ trim($name) } = trim($val);
}
close(F);
my $current_host = $properties{host_server};
my $token = $properties{server_token};
my $state = 'success';
my $monitor_freq = $properties{monitor_frequency};
错误
syntax error at Q:/IDE/Eclipse_Workspace/ICEFaces/Server_Client_Mon/Server_Client_Mon.pl line 22, near "$properties{ "
Global symbol "$val" requires explicit package name at Q:/IDE/Eclipse_Workspace/ICEFaces/Server_Client_Mon/Server_Client_Mon.pl line 22.
Global symbol "%properties" requires explicit package name at Q:/IDE/Eclipse_Workspace/ICEFaces/Server_Client_Mon/Server_Client_Mon.pl line 25.
Global symbol "%properties" requires explicit package name at Q:/IDE/Eclipse_Workspace/ICEFaces/Server_Client_Mon/Server_Client_Mon.pl line 26.
Global symbol "%properties" requires explicit package name at Q:/IDE/Eclipse_Workspace/ICEFaces/Server_Client_Mon/Server_Client_Mon.pl line 28.
Global symbol "%properties" requires explicit package name at Q:/IDE/Eclipse_Workspace/ICEFaces/Server_Client_Mon/Server_Client_Mon.pl line 32.
答案 0 :(得分:6)
将声明移到循环之外
my %properties;
while(...) {
...
$properties{ trim($name) } = trim($val)
}
答案 1 :(得分:3)
像这样:
open my $fh, '<', 'properties' or die "Unable to open properties file: $!";
my %properties;
while (<$fh>) {
next if /^#/;
my ($name, $val) = map trim($_), split /=/, $_, 2;
$properties{$name} = $val;
}
my ($current_host, $token, $monitor_freq) =
@properties{qw/ host_server server_token monitor_frequency /};
my $state = 'success';
答案 2 :(得分:1)
如果你不介意一点额外的内存使用,
my %properties = map {
/^#/ ? ()
: map trim($_), /(\w+)\s*=(.+)/;
}
<F>;
或
my %properties =
map trim($_),
map /(\w+)\s*=(.+)/,
grep !/^#/, <F>;