什么是 Perl 的功能,postderef?

5
我看到在Moxie这里第8行使用了use experimental 'postderef'use feature 'postderef'。我只是对它的作用感到困惑。关于experimental的手册也相当模糊。

允许使用后缀解引用表达式,包括在插值字符串中

有人能展示一下没有使用该编译指示时需要做什么,以及该编译指示使得什么更容易或可能吗?

1个回答

7

这是什么

这很简单。它是一种具有优点和缺点的语法糖。由于该功能在5.24中已成为核心功能,因此不再需要pragma。但是为了支持5.20到5.24之间的版本,必须使用以下命令启用:use experimental 'postderef'。在提供的示例中,在Moxie中,它在一行中使用了$meta->mro->@*;没有它,您将不得不写@{$meta->mro}

概要

这些直接来自D Foy的博客,以及我编写的惯用Perl进行比较。

D Foy example                    Idiomatic Perl
$gimme_a_ref->()->@[0]->%*       %{ $gimme_a_ref->()[0] }
$array_ref->@*                   @{ $array_ref }
get_hashref()->@{ qw(cat dog) }  @{ get_hashref() }{ qw(cat dog) }

这些例子是由 D Foy 提供的,

D Foy example                    Idiomatic Perl
$array_ref->[0][0]->@*           @{ $array_ref->[0][0] }
$sub->&*                         &some_sub

支持的理由

  • postderef 允许链接多个引用。
  • postderef_qq 使复杂的字符串内插更容易。

反对的理由

D Foy 并未提供任何反对理由。

  • Loses sigil significance. Whereas before you knew what the "type" was by looking at the sigil on the left-most side. Now, you don't know until you read the whole chain. This seems to undermine any argument for the sigil, by forcing you to read the whole chain before you know what is expected. Perhaps the days of arguing that sigils are a good design decision are over? But, then again, perl6 is still all about them. Lack of consistency here.
  • Overloads -> to mean, as type. So now you have $type->[0][1]->@* to mean dereference as $type, and also coerce to type.
  • Slices do not have an similar syntax on primitives.

    my @foo = qw/foo bar baz quz quuz quuuz/;
    my $bar = \@foo;
    
    # Idiomatic perl array-slices with inclusive-range slicing
    say @$bar[2..4];   # From reference; returns bazquzquuz
    say @foo[2..4];    # From primitive; returns bazquzquuz
    
    # Whizbang thing which has exclusive-range slicing
    say $bar->@[2,4];  # From reference; returns bazquz
                       # Nothing.
    

来源


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接