加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 06:28:55 所属栏目:大数据 来源:网络整理
导读:我可以在其中创建一个带有“空插槽”的数组: $perl -wde 1... DB1 $x[2] = 0 DB2 x @x0 ARRAY(0x103d5768) 0 empty slot 1 empty slot 2 0 要么 DB3 $#y = 4 DB4 x @y 0 ARRAY(0x103d5718) 0 empty slot 1 empty slot 2 empty slot 3 empty slot 4 empty
我可以在其中创建一个带有“空插槽”的数组:

$perl -wde 1
...
  DB<1> $x[2] = 0
  DB<2> x @x
0  ARRAY(0x103d5768)
   0  empty slot
   1  empty slot
   2  0

要么

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

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

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

这不起作用:

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

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

DB<6> x []->[2] = 0
0  0

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

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

感谢您的任何见解.

解决方法

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.

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

我不能说存在记录的行为存在.所以不能保证它不会有一天改变.但它适用于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."

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读