gpt4 book ai didi

perl - 如何获取列表以显示 Perl 中空条目的零?

转载 作者:行者123 更新时间:2023-12-04 11:08:06 26 4
gpt4 key购买 nike

最初,我正在处理一个长度为 2^16 的列表。然而,为了抽象这一点,我将在这个例子中设置 length = 5。

#subroutine to make undefined entries -> 0
sub zeros {
foreach(@_) {
if(!defined($_)) {
$_ = 0;
}
}
}
#print out and indicies and elements of list
sub checking {
print "List = \n";
my $counter = 0;
foreach (@_) {
print "index = $counter\n";
print "$_\n";
$counter += 1;
}
print "\n";
}

方法一 :如果我访问不同的索引来编辑元素,当我打印出数组时,我会得到以下信息。 我不想看到空白。我希望它们是 0 .我已经设置了一个子程序“zeros”来使未定义的条目变为零。但我不知道我的代码出了什么问题。我还为列表的每个元素尝试了“$_ += 0”。我仍然无法为空条目获得零。
#method 1
@abc = ();
$abc[1] = 3;
$abc[5] = 5;
&zeros(@abc);
&checking(@abc);
List =
index = 0

index = 1
3
index = 2

index = 3

index = 4

index = 5
5

方法 2 :如果我像这样初始化列表,我可以得到零。但是正如我所说,我正在处理很长的列表,我绝对不能像这样初始化我的列表。
#method 2
@abc = (3,0,0,0,5);
&checking(@abc);

List =
index = 0
3
index = 1
0
index = 2
0
index = 3
0
index = 4
5

最佳答案

你可以使用初始化你的列表

@abc = (0) x 2**16 

它将它设置为 2**16 个零的列表?

我尝试使用您的零点方法。如果我像这样初始化数组,它会起作用:
@abc = (undef, 1, undef, undef, undef, 5)

所以看起来子程序不会替换不存在的数组条目(而不是存在但值为 undef )

在这种情况下,您可以尝试扩展您的 zeros返回修改后的数组并将其分配回原始数组的子例程:
#subroutine to make undefined entries -> 0
sub zeros {
foreach(@_) {
if(!defined($_)) {
$_ = 0;
}
}
return @_;
}

@abc = ();
$abc[1] = 3;
$abc[5] = 5;
@abc = zeros(@abc);
# Check:
print "index = $_\n$abc[$_]\n" for 0..$#abc;

或者,您可以传递对原始数组的引用:
#subroutine to make undefined entries -> 0
sub zeroref {
my ($array) = @_; # Expect a single argument: An array-reference
foreach(@$array) {
if(!defined($_)) {
$_ = 0;
}
}
}

@abc = ();
$abc[1] = 3;
$abc[5] = 5;
zeroref(\@abc); # Pass an array-reference instead
# Check:
print "index = $_\n$abc[$_]\n" for 0..$#abc;

关于perl - 如何获取列表以显示 Perl 中空条目的零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18090182/

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