无法解析 Perl 数组中的标量

Can't resolve scalars from Perl arrays

我有一个对散列 $conf 的 Perl 引用,它有一个数组作为值之一。我可以通过以下方式检索它:

$conf->{group}->{names} # returns an array (NOT array ref)

但是当我将它存储在其他变量中时,我得到了这种异常行为。

say ($conf->{group}->{names}); # some array ref
say ($conf->{group}->{names}[1]); # some string
my @list = $conf->{group}->{names};
say ($list[0]); # same array ref

造成这种行为的原因可能是什么?我想遍历这个数组,但使用 foreach 但因此无法这样做。

我想遍历数组的元素,但我不知道该怎么做。

您声称 $conf->{group}->{names} 是一个数组而不是对数组的引用,但这是不可能的。哈希值是标量;它们不能是数组。这就是为什么我们在散列中存储对数组的引用。

$conf->{group}->{names}[1] 有效($conf->{group}->{names}->[1] 的缩写)表明 $conf->{group}->{names} 它是对数组的引用。[1]

您将此引用分配给 @list,因此用此引用填充 @list。这就是为什么 $list[0] 是这个引用。


您希望遍历数组的元素。如果你有一个命名数组,你会使用

for (@array) {
   ...
}

但是你有一个数组的引用。有两种语法可用于完成此操作。

  1. circumfix 语法的特点是 returns 引用

    for (@{ $ref }) {   # Or just @$ref when the block contains a simple scalar.
       ...
    }
    

    在你的情况下,

    my $ref = $conf->{group}{names}[1];
    for (@$ref) {
       ...
    }
    

    for (@{ $conf->{group}{names}[1] }) {
       ...
    }
    
  2. 可以将后缀(又名“箭头”)语法功能添加到表达式中。

    for ($ref->@*) {
       ...
    }
    

    在你的情况下,

    my $ref = $conf->{group}{names}[1];
    for ($ref->@*) {
       ...
    }
    

    for ($conf->{group}{names}[1]->@*) {
       ...
    }
    

    ->@* 需要 Perl 5.24+。通过添加 use feature qw( postderef );no warnings qw( experimental::postderef ); 或添加 use experimental qw( postderef );,它在 Perl 5.20+ 中可用。这是安全的,因为当时的实验特性被 Perl 接受而没有改变。

参见 及其链接的文档。


  1. 我假设您正在像往常一样使用 use strict;