code_junkie

Why does this map statement in Perl not compile?

Nov 12th, 2011
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. my @a = ("a", "b", "c", "d", "e");
  2. my %h = map { "prefix-$_" => 1 } @a;
  3.  
  4. Not enough arguments for map at foo.pl line 4, near "} @a"
  5.  
  6. my @a = ("a", "b", "c", "d", "e");
  7. my %h = map { "prefix-" . $_ => 1 } @a;
  8.  
  9. my @a = ("a", "b", "c", "d", "e");
  10. my %h = map { +"prefix-$_" => 1 } @a;
  11.  
  12. my %h = map { ("prefix-$_" => 1) } @a;
  13.  
  14. "{" starts both hash references and blocks, so "map { ..."
  15. could be either the start of map BLOCK LIST or map EXPR, LIST.
  16. Because perl doesn’t look ahead for the closing "}" it has to
  17. take a guess at which its dealing with based what it finds just
  18. after the "{". Usually it gets it right, but if it doesn’t it
  19. won’t realize something is wrong until it gets to the "}" and
  20. encounters the missing (or unexpected) comma. The syntax error
  21. will be reported close to the "}" but you’ll need to change
  22. something near the "{" such as using a unary "+" to give perl
  23. some help:
  24.  
  25. %hash = map { "L$_", 1 } @array # perl guesses EXPR. wrong
  26. %hash = map { +"L$_", 1 } @array # perl guesses BLOCK. right
  27. %hash = map { ("L$_", 1) } @array # this also works
  28. %hash = map { lc($_), 1 } @array # as does this.
  29. %hash = map +( lc($_), 1 ), @array # this is EXPR and works!
  30. %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array)
  31.  
  32. or to force an anon hash constructor use "+{"
  33.  
  34. @hashes = map +{ lc($_), 1 }, @array # EXPR, so needs , at end
  35.  
  36. and you get list of anonymous hashes each with only 1 entry.
  37.  
  38. my @a = qw( a b c d e );
  39. my %h;
  40. @h{@a} = ();
  41.  
  42. @h{@a} = (1) x @a;
  43.  
  44. @h{$_} = 1 for @a;
  45.  
  46. map { ; "prefix-$_" => 1 } @a;
Add Comment
Please, Sign In to add comment