2013-11-20 27 views
1

当我使用严格的,我得到下面的编译问题,否则它工作正常。我试图将“我的”关键字放在属性中,但这并没有解决它。我做错了什么?全局符号“%properties”需要明确的包名

#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

变量的声明中无法分配到一个哈希键。你必须始终执行'my%hash; $ hash {foo} = ...'分成两行,除非你一次赋值整个散列:'my%hash =(foo => bar,baz => baaz);'。 – TLP

回答

6

举动外循环声明

my %properties; 
while(...) { 
    ... 
    $properties{ trim($name) } = trim($val) 
} 
+0

如果我有如下sub sub client_monitor_state(){ \t my $ token = $ properties {token}; },它无法找到属性?如何解决这个问题? – user1595858

+0

如果'my%properties'出现在它之前,它可以找到它。 – ikegami

+1

不要使用原型,除非你知道他们在做什么(你的子名称后面是空的parens)。 – TLP

1

如果你不介意点点额外的内存使用情况,

my %properties = map { 
    /^#/ ?() 
     : map trim($_), /(\w+)\s*=(.+)/; 
} 
<F>; 

my %properties = 
    map trim($_), 
    map /(\w+)\s*=(.+)/, 
    grep !/^#/, <F>; 
+0

...但你确实想说'我的$ properties = map trim($ _),map /(\w+)\s*=(.+)/,grep!/ ^#/,'。 – amon

+0

@amon如果你的意思是'%属性',那么是的。有没有对多个地图/ greps的缺点? –

+0

对不起,当然我的意思是哈希。是的,使用'map'和'grep'存在缺点,因为所有这些列表操作都将整个中间数据存储在堆栈上 - 但我们的两个解决方案在这方面是等价的。我的评论只是想指出'map {COND? EXPR:()}'更习惯地表示为'map {EXPR} grep {COND}'。此外,在“尾部位置”中嵌套的“地图”可以变平:map {map B($ _),A($ _)}'与map B($ _)相同,map A($ _)'。 – amon

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'; 
相关问题