2008-11-07 3 views

답변

21

왜냐하면 Perl은 BLOCK 대신 EXPR (예 : 해시 참조)을 추측하기 때문입니다. 이합니다 ('+'기호 주) 작동합니다 :

my @a = ("a", "b", "c", "d", "e"); 
my %h = map { +"prefix-$_" => 1 } @a; 

http://perldoc.perl.org/functions/map.html를 참조하십시오. perldoc -f map에서

11

는 :

  "{" starts both hash references and blocks, so "map { ..." 
      could be either the start of map BLOCK LIST or map EXPR, LIST. 
      Because perl doesn’t look ahead for the closing "}" it has to 
      take a guess at which its dealing with based what it finds just 
      after the "{". Usually it gets it right, but if it doesn’t it 
      won’t realize something is wrong until it gets to the "}" and 
      encounters the missing (or unexpected) comma. The syntax error 
      will be reported close to the "}" but you’ll need to change 
      something near the "{" such as using a unary "+" to give perl 
      some help: 

      %hash = map { "\L$_", 1 } @array # perl guesses EXPR. wrong 
      %hash = map { +"\L$_", 1 } @array # perl guesses BLOCK. right 
      %hash = map { ("\L$_", 1) } @array # this also works 
      %hash = map { lc($_), 1 } @array # as does this. 
      %hash = map +(lc($_), 1), @array # this is EXPR and works! 
      %hash = map (lc($_), 1), @array # evaluates to (1, @array) 

      or to force an anon hash constructor use "+{" 

      @hashes = map +{ lc($_), 1 }, @array # EXPR, so needs , at end 

      and you get list of anonymous hashes each with only 1 entry. 
13

나는 2 요소 목록을 반환 오전

my %h = map { ("prefix-$_" => 1) } @a; 

로하는 것은, 의도를 보여주고 있음을 쓰는 것을 선호합니다.

6

또한, 다른 방법은 당신이하고있는 해시를 초기화하고 일을하기 위해 다음과 같이 할 수 있습니다 다섯 개 키 각각에 대해 미확정 항목을 작성합니다

my @a = qw(a b c d e); 
my %h; 
@h{@a} =(); 

합니다. 그들에게 모든 진정한 가치를 부여하고 싶다면 이것을하십시오.

루프를 사용하여 명시 적으로 지정할 수도 있습니다.

@h{$_} = 1 for @a; 
1

나는

map { ; "prefix-$_" => 1 } @a; 

은 지금까지 그것이 문장의 블록이 아닌 해시 심판임을 지정으로, 더 관용적이라고 생각합니다. 당신은 그냥 null 진술로 걷어차 고 있습니다.

관련 문제