2013-11-20 25 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'; 
相關問題