Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to get the last N elements of a Perl array?

Tags:

What's the best way to get the last N elements of a Perl array?

If the array has less than N, I don't want a bunch of undefs in the return value.

like image 571
mike Avatar asked Mar 04 '09 17:03

mike


People also ask

How do you find the last n elements of an array?

To get the last N elements of an array, call the slice method on the array, passing in -n as a parameter, e.g. arr. slice(-3) returns a new array containing the last 3 elements of the original array.

How do I get the last element of an array in Perl?

Perl provides a shorter syntax for accessing the last element of an array: negative indexing. Negative indices track the array from the end, so -1 refers to the last element, -2 the second to last element and so on.

What does Unshift do in Perl?

unshift() function in Perl places the given list of elements at the beginning of an array. Thereby shifting all the values in the array by right. Multiple values can be unshift using this operation. This function returns the number of new elements in an array.


1 Answers

@last_n = @source[-$n..-1];

If you require no undefs, then:

@last_n = ($n >= @source) ? @source : @source[-$n..-1];
like image 161
chaos Avatar answered Oct 16 '22 16:10

chaos