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.
From stackoverflow
-
I think what you want is called a slice.
-
my $size = (scalar @list) - 1; my @newList = @list[$size-$n..$size];
chaos : Doesn't work. You need the .. sigil, not comma, and $size is too large by one.Tim Howland : you're right, too much time in groovy- I'll edit to matchchaos : May as well just say $#list like Nathan instead of putting scalar(@list) - 1 in a variable.Tim Howland : I thought about that- since the OP was new to perl, I thought it would be better to avoid the $# construction, in favor of the more straightforward scalar call- I remember hating all the wacky special variables when I was getting started.mike : Who said I'm new to Perl? -
@last_n = @source[-$n..-1];If you require no
undefs, then:@last_n = $n >= @source ? @source : @source[-$n..-1];mike : That doesn't work if @source has fewer than $n items.chaos : It work okay. undefs go into @last_n in the positions for which @source has no values, which is correct for some not-entirely-unreasonable semantics of what it means to "take the last N elements".Nathan : oh, I've never used negative subscripts like that, I learned something today!Schwern : That's pretty clever!Telemachus : @Chaos: I'm putting this here since you wouldn't see a comment on the main post. What's with all the scrubbing and polishing of old, answered questions lately? You've got too much rep to be looking for more (and I know it's not your style). Bored at work? :)brian d foy : What's wrong with improving your answers? -
@a = (a .. z); @last_five = @a[ $#a - 4 .. $#a ]; say join " ", @last_five;outputs:
v w x y z
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.