简体   繁体   中英

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 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,

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 :

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM