【问题标题】:What does `sub bar { +{$_[1] => $_[2]} }` exactly do?`sub bar { +{$_[1] => $_[2]} }` 到底是做什么的?
【发布时间】:2015-09-20 23:26:34
【问题描述】:

我不明白这个例子中的 + 糖符号是在护目镜时在某处拍摄的:

sub bar { +{$_[1] => $_[2]} }

我写了这个,在这里我看不出有什么不同:

use Data::Dumper;

# Not any differences here
my $foo =  {value => 55};
my $bar = +{value => 55};

print Dumper $foo;
print Dumper $bar;

# Oh ! Here there is something...
sub foo {  {$_[1] => $_[2]} };
sub bar { +{$_[1] => $_[2]} };

print Dumper foo('value', 55);    
print Dumper bar('value', 55);    

foo 返回

$VAR1 = 55;
$VAR2 = undef;

bar 返回

$VAR1 = {
          '55' => undef
        };

【问题讨论】:

  • 你已经在使用 Data::Dumper,所以我简化了它,让它可以被更多人运行

标签: perl hash


【解决方案1】:

它帮助解析器区分匿名哈希和代码块。

引用Learning Perl Objects, References & Modules

因为块和匿名哈希构造函数都在语法树中大致相同的位置使用花括号,所以编译器必须临时确定你指的是哪一个。如果编译器的决定不正确,您可能需要提供一个提示来获得您想要的东西。要向编译器显示您需要匿名哈希构造函数,请在左大括号前放置一个加号:+{ ... }。为了确保得到一个代码块,只需在代码块的开头放一个分号(代表一个空语句):{; ... }。

或者来自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 it's dealing with based on 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 "+" or semicolon 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 { ("\L$_" => 1) } @array # as does this
    %hash = map {  lc($_) => 1  } @array # and 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
                                           # comma at end

to get a list of anonymous hashes each with only one entry apiece.

【讨论】:

  • 用什么方法可以找到这个文档?我试着盯着perl "+{}" and perl "+{ ... }"` 甚至perl plus sign hash。我没有找到任何相关的东西。你的魔术是什么?
  • 我通过阅读 map perldoc.perl.org/functions/map.html 上的文档“知道”
  • 我在 Google 上搜索了“perl 哈希加号”并将链接作为第一个点击。
  • @Sobrique 感谢您的参考:我将其添加到答案中
  • @nowox 您也可以尝试使用symbolhound.com,这对于搜索谷歌删除的内容很有用
猜你喜欢
  • 2015-08-06
  • 2013-09-02
  • 2014-01-02
  • 2013-10-10
  • 2017-05-08
  • 2022-01-20
  • 2012-10-17
  • 2017-06-15
  • 2011-05-20
相关资源
最近更新 更多