Reputation: 311
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 e.g., I have an array of zeros. And I want to initialize elements 4 to 9 as 1. I would think of doing something like,
my @array = (0) x 10;
for my $i (3 .. 8) {
$array[$i] = 1;
}
Upvotes: 1
Views: 2350
Reputation: 57600
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
.
Instead of supplying a single index, we use a list [3..8]
. We have to adjust the sigil to @
, because we want a list context.
Upvotes: 5
Reputation: 183251
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
:
splice @array, 3, 6, (1) x 6;
Upvotes: 5