Perlのこのmapステートメントがコンパイルされないのはなぜですか?
質問
これは失敗します:
my @a = ("a", "b", "c", "d", "e");
my %h = map { "prefix-これは失敗します:
Not enough arguments for map at foo.pl line 4, near "} @a"
このエラー:
my @a = ("a", "b", "c", "d", "e");
my %h = map { "prefix-" . これは失敗します:
my @a = ("a", "b", "c", "d", "e");
my %h = map { "prefix-これは失敗します:
Not enough arguments for map at foo.pl line 4, near "} @a"
このエラー:
<*>
しかし、これは動作します:
<*>
なぜ?
" => 1 } @a;
このエラー:
<*>
しかし、これは動作します:
<*>
なぜ?
=> 1 } @a;
しかし、これは動作します:
<*>
なぜ?
" => 1 } @a;
このエラー:
<*>しかし、これは動作します:
<*>なぜ?
解決
PerlはBLOCKではなくEXPR(たとえば、ハッシュ参照)を推測しているためです。これは動作するはずです(「+」記号に注意してください):
my @a = ("a", "b", "c", "d", "e");
my %h = map { +"prefix- PerlはBLOCKではなくEXPR(たとえば、ハッシュ参照)を推測しているためです。これは動作するはずです(「+」記号に注意してください):
<*>
http://perldoc.perl.org/functions/map.html をご覧ください。 。
" => 1 } @a;
http://perldoc.perl.org/functions/map.html をご覧ください。 。
他のヒント
私はそれを次のように書くことを好みます
my %h = map { ("prefix-私はそれを次のように書くことを好みます
<*>
2要素のリストを返すという意図を示すため。
" => 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 perldoc -f map
から:
<*>", 1 } @array # perl guesses EXPR. wrong
%hash = map { +"\L perldoc -f map
から:
<*>", 1 } @array # perl guesses BLOCK. right
%hash = map { ("\L perldoc -f map
から:
<*>", 1) } @array # this also works
%hash = map { lc( perldoc -f map
から:
<*>), 1 } @array # as does this.
%hash = map +( lc( perldoc -f map
から:
<*>), 1 ), @array # this is EXPR and works!
%hash = map ( lc( perldoc -f map
から:
<*>), 1 ), @array # evaluates to (1, @array)
or to force an anon hash constructor use "+{"
@hashes = map +{ lc( perldoc -f map
から:
<*>), 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{また、ハッシュを初期化して、あなたがやっていることを行う別の方法は、次のようにすることができます:
my @a = qw( a b c d e );
my %h;
@h{@a} = ();
これにより、5つのキーのそれぞれにundefエントリが作成されます。すべての値を真にしたい場合は、これを実行します。
@h{@a} = (1) x @a;
ループで明示的に行うこともできます。
<*>} = 1 for @a;
そう思う
map { ; "prefix-そう思う
<*>
は、ハッシュ参照ではなくステートメントのブロックであることを指定する限り、より慣用的です。 nullステートメントで開始するだけです。
" => 1 } @a;
は、ハッシュ参照ではなくステートメントのブロックであることを指定する限り、より慣用的です。 nullステートメントで開始するだけです。