문제

이것은 실패합니다 :

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

이 오류로 :

Not enough arguments for map at foo.pl line 4, near "} @a"

그러나 이것은 작동합니다 :

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

왜요?

도움이 되었습니까?

해결책

Perl은 블록 대신 EXPR (예 : 해시 참조)을 추측하기 때문입니다. 작동해야합니다 ( '+'기호 참고) :

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

보다 http://perldoc.perl.org/functions/map.html.

다른 팁

나는 그것을 다음과 같이 쓰는 것을 선호합니다

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

의도를 보여주기 위해 2 요소 목록을 반환하고 있습니다.

에서 perldoc -f map:

           "{" 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.

또한, 당신이하고있는 일을하는 다른 방법, 해시 초기화, 당신은 다음과 같이 할 수 있습니다.

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

5 개의 키 각각에 대해 undef 항목이 생성됩니다. 당신이 그들에게 모든 진정한 가치를주고 싶다면, 이것을하십시오.

@h{@a} = (1) x @a;

루프로 명시 적으로 할 수 있습니다.

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

내 생각에는

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

해시 참조가 아니라 진술의 블록임을 명시하는 한 더 관용적입니다. 당신은 단지 널 진술로 그것을 시작하고 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top