2013-11-20 2 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 => bar, baz => baaz);'한 번에 전체 해시를 지정하지 않는 한 두 줄로 $ hash {foo} = ...'. – TLP

답변

6

이동 루프 밖에서 선언

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

하위에 하위가있는 경우 어떻게합니까? client_monitor_state() { \t my $ token = $ properties {token}; }, 그것은 바로 속성을 찾을 수 없습니까? 이 문제를 해결하는 방법? – user1595858

+0

'my % properties;가 그 앞에 오는 경우 찾을 수 있습니다. – ikegami

+1

프로토 타입을 사용하지 않는 한 프로토 타입을 사용하지 마십시오 (하위 이름 뒤에 빈 괄호가 있음). – TLP

1

당신이 약간의 여분의 메모리 사용을 꺼리지 않는 경우,

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

또는

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

...하지만 정말로 'my $ properties = map trim ($ _), map /(\w+)\s*=(()+/)/, grep!/^ # /, '라고 말하려고했습니다. – amon

+0

@amon 만약 당신이'% properties'를 의미했다면 그렇습니다. 여러 맵/greps에 단점이 있습니까? –

+0

미안하지만 물론 해시를 의미합니다. 예,'map'과'grep'을 사용하는 데에는 단점이 있습니다. 왜냐하면 그러한 모든 목록 연산은 전체 중간 데이터를 스택에 저장하기 때문입니다. 그러나이 두 가지 해법은 동등합니다. 내 의견은 단지'map {COND? EXPR :()}'는 idomatically'map {EXPR} grep {COND}'로 표현됩니다. 'map ($ _), 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'; 
관련 문제