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;
}
Why not use an array slice?
This is easier to understand than a
spliceand clearer than amap.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.