gpt4 book ai didi

arrays - perl中的$ {…}到底是什么意思?

转载 作者:行者123 更新时间:2023-12-04 13:23:29 24 4
gpt4 key购买 nike

考虑下。有一个 list

qw(a b c);

现在,将LIST分配给无名(匿名)ARRAY
[ qw(a b c) ]

所以下一个
use 5.016;
use warnings;
use diagnostics;
my $x = [ qw(a b c) ];
say ref $x; #ARRAY - the $x is an ARRAY reference, and
say $x->[1]; #prints "b", and
say [ qw(a b c) ]->[1]; #works too

但是现在发生了什么?
use 5.016;
use warnings 'all';
use diagnostics;
say ${[ qw(a b c) ]}[1];

它打印 b,但是
my $y = ${[ qw(a b c) ]};

是一个错误,
Not a SCALAR reference at pepe line 6 (#1)
(F) Perl was trying to evaluate a reference to a scalar value, but found
a reference to something else instead. You can use the ref() function
to find out what kind of ref it really was. See perlref.

Uncaught exception from user code:
Not a SCALAR reference at pepe line 17.

那么,什么是构造$ {....}
  • 它在say中“起作用”(打印匿名数组的第二个元素),但是不明白为什么
  • ,但不能将其分配给变量
  • diagnostics中的提示不是很有帮助,因为在无法分配时应该如何使用 ref?我从 perlref中错过了什么?

    最佳答案

    ${ EXPR1 }[ EXPR2 ]是数组索引取消引用。它返回由EXPR2返回的引用所引用的数组的EXPR1返回的索引处的元素。
    ${ $array_ref }[ ... ]用于数组引用,就像$array[...]用于数组一样。

    后面没有${ EXPR }[{是标量取消引用。它返回EXPR返回的引用所引用的标量。
    ${ $scalar_ref }用于标量引用,而$scalar用于标量。

    如您所见,在处理引用时,可以使用与通常相同的语法,只是用{$ref}替换了变量的名称(保留前导符号)。

    这样,@{ $array_ref }用于数组引用,就像@array用于数组一样。

    say @{[ qw(a b c) ]};

    这是我之前的 Mini-Tutorial: Dereferencing Syntax中图表的本质。也可以看看:
  • References quick reference
  • perlref
  • perlreftut
  • perldsc
  • perllol


  • 糟糕,我以为你有
    say ${[ qw(a b c) ]};   # Want to print a b c

    你有
    my $y = ${[ qw(a b c) ]};

    你要
    my $y = [ qw(a b c) ];
    []创建一个数组和对该数组的引用,并返回后者,有点像
    my $y = do { my @anon = qw(a b c); \@a };

    关于arrays - perl中的$ {…}到底是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16531756/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com