Iterate over first at most n elements of an perl array

Viewed 2766

What is the most pleasant idiomatic way of writing

for (take(100,@array)) {...}

given that there is no take (which takes the first n elements of a list, but fewer if there are not n elements)?

Things I considered:

  • for (@array[0..99]) {...}

    but that fails ungraceful if @array has fewer than 100 elements

  • for (@array[0..min(99,$#array)]) {...}

    but min is not a standard function in Perl

  • for (splice @array,0,100) {...}

    bu that changes the array.

7 Answers
Related