I wanted to chop off all but the first five elements of an array, so I stupidly did:
@foo = @foo[ 0 .. 4 ];
and heartily praised my own cleverness. But that broke once @foo ended up with only three elements, because then I ended up with two undefs on the end, instead of a three-element array. So I changed it to:
@foo = @foo > 5 ? @foo[ 0 .. 4 ] : @foo;
This works but is kinda ugly. Is there a better idiom for saying “give me everything up to the first five elements of the array?”
You can set the last index of an array to shorten or lengthen it. Like your code you’ll need to check to make sure your not creating undef elements.