[英]How to assign a group of array elements a value in Perl?
I want to initialize a group of array elements the same value using a single line. 我想使用一行初始化一组具有相同值的数组元素。 I know I could use a for loop, but I want to know if there is a way simpler way to do it. 我知道我可以使用for循环,但是我想知道是否有一种更简单的方法可以做到这一点。
for eg, I have an array of zeros. 例如,我有一个零数组。 And I want to initialize elements 4 to 9 as 1. I would think of doing something like, 我想将元素4到9初始化为1。我想做些类似的事情,
my @array = (0) x 10;
for my $i (3 .. 8) {
$array[$i] = 1;
}
One approach: 一种方法:
my @array = (0) x 3, (1) x 6, 0;
Another approach: 另一种方法:
my @array = map { $_ >= 3 && $_ <= 8 ? 1 : 0 } (0 .. 9);
Or, if you mean that you've already set @array
to (0) x 10
, and are just looking for a one-liner to set a range of values to 1
: 或者,如果您的意思是已经将@array
设置为(0) x 10
,并且只是在寻找一种将值范围设置为1
:
splice @array, 3, 6, (1) x 6;
Why not use an array slice? 为什么不使用数组切片?
@array = (0) x 10;
@array[3..8] = (1) x 6; # or something > 6
This is easier to understand than a splice
and clearer than a map
. 这splice
更容易理解,比map
更清晰。
Instead of supplying a single index, we use a list [3..8]
. 而不是提供单个索引,我们使用列表[3..8]
。 We have to adjust the sigil to @
, because we want a list context. 我们必须将标记调整为@
,因为我们需要列表上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.