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.
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.
If you require no
undef
s, then:simple, no math:
TMTOWTDI, but I think this is a bit easier to read (but removes the elements from
@source
):And if you are not sure that
@source
has at least$n
elements:outputs:
As @a in scalar context gives the length on an array a and because
@a == $#a + 1
(unless$[
is set to non-zero), one can get the slice from the $nth (counting from zero) to to last element by@a[$n..@a-1]
-- #tmtowtdi.I think what you want is called a slice.