开发者

How can i create an array and auto populate the elements in perl

lets say i have an array :

@time = qw( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 3开发者_如何学C8 39 40 41 42 43 44 45 46 47 48 49 50 );

but the values 1..50 depend on the size of an array @arr

so instead of declaring @time manually, how can i populate @time with 1 .. @arr, and possibly have other TYPES of elements like TIME in seconds, etc.


This will initialise @time with the values from 1 to $#arr:

@time = (1..$#arr);

I suspect you probably want 0 .. $#arr rather than 1 .. $#arr?

and possibly have other TYPES of elements like TIME in seconds, etc.

I'm not quite sure what you mean here, but you should have a look at map for one convenient way of generating a list of values by transforming another list. That might be what you're after.


@time = 1 .. @arr;

If you want to do something with each number, like multiply them by 2, you can use map:

@time = map { 2 * $_ } 1 .. @arr;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜