如何用'空槽'创建一个匿名数组([])?

hex*_*der 5 perl anonymous-arrays

我可以在其中创建一个带有"空插槽"的数组:

$ perl -wde 1
...
  DB<1> $x[2] = 0
  DB<2> x \@x
0  ARRAY(0x103d5768)
   0  empty slot
   1  empty slot
   2  0
Run Code Online (Sandbox Code Playgroud)

要么

  DB<3> $#y = 4
  DB<4> x \@y  
0  ARRAY(0x103d5718)
   0  empty slot
   1  empty slot
   2  empty slot
   3  empty slot
   4  empty slot
Run Code Online (Sandbox Code Playgroud)

请注意:这与分配不同undef.

但是如何使用[和指定匿名数组]呢?

这不起作用:

  DB<5> x [,,0]
syntax error at (eval 27)[/usr/local/lib/perl5/5.10.0/perl5db.pl:638] line 2, near "[,"
Run Code Online (Sandbox Code Playgroud)

这也失败了,因为我只得到指定的值:

  DB<6> x []->[2] = 0
0  0
Run Code Online (Sandbox Code Playgroud)

额外问题:如何在Perl脚本中检查"空数组槽"?

背景:在我的测试脚本中,我希望能够精确地比较数组内容.例如,我想区分"未分配"和"分配了undef值".

感谢您的任何见解.

Dav*_*idO 5

use feature qw/ say /;
use strict;
use warnings;

my $aref;

$#{$aref} = 4;
$aref->[2] = undef;
$aref->[3] = '';

foreach my $idx ( 0 .. $#{$aref} ) {
    say "Testing $idx.";
    say "\t$idx exists." if exists $aref->[$idx];
    say "\t$idx defined." if defined $aref->[$idx];
}

OUTPUT:
Testing 0.
Testing 1.
Testing 2.
    2 exists.
Testing 3.
    3 exists.
    3 defined.
Testing 4.
Run Code Online (Sandbox Code Playgroud)

我们在匿名数组中预先分配了五个点,@{$aref}.最高指数是4.我们能够找到与我们创建它的方式相同的顶级索引; 通过测试的价值$#{$aref}.我们可以测试存在.我们知道之间的所有内容0,并4已创建.但Perl只报告"存在"数组元素,这些数组元素已经分配给它们(即使它是undef).因此,$aref->[2]据报道存在,但未定义.为了好玩,我们分配''$aref->[3]一次定义的测试报告.但短篇小说是即使阵列是预扩展的,我们仍然可以通过使用' ' 来测试正在初始化undef的元素与undef通过数组预扩展的元素之间的差异exists.

我不能说这是记录在案的行为exists.所以不能保证它不会有一天改变.但它适用于5.8,5.10,5.12和5.14.

因此,寻找一种简单的方法来查找哪些元素已初始化,哪些已定义,哪些不是,这是一个示例:

use feature qw/ say /;
use strict;
use warnings;

my $aref;

$#{$aref} = 4;
$aref->[2] = undef;
$aref->[3] = '';

my @initialized = grep { exists $aref->[$_] } 0 .. $#{$aref};
my @defined = grep { defined $aref->[$_] } 0 .. $#{$aref};
my @uninitialized = grep { not exists $aref->[$_] } 0 .. $#{$aref};
my @init_undef = grep { exists $aref->[$_] and not defined $aref->[$_] } 0 .. $#{$aref};
say "Top index is $#{$aref}.";
say "These elements are initialized: @initialized.";
say "These elements are not initialized: @uninitialized.";
say "These elements were initialized with 'undef': @init_undef.";
say "These elements are defined: @defined."
Run Code Online (Sandbox Code Playgroud)