On Wed, 12 Apr 2017 18:16:56 -0400 Uri Guttman <u...@stemsystems.com> wrote:
> On 04/12/2017 05:42 PM, Shawn H Corey wrote: > > On Wed, 12 Apr 2017 16:19:32 -0400 > > Uri Guttman <u...@stemsystems.com> wrote: > > > > > > my @array; > > > > for my $index (reverse sort @indices) { > >> sort defaults to a lexical sort which won't work well on integers > >> with more than 2 digits. > >> > >> and why are you sorting and reversing the indexes? i don't think > >> that will help make the splice more efficient if any of the > >> indexes are not at the end of the array. > > If you're going to splice, do it from the highest index to the > > lowest. Otherwise the splice will shift the end of the array down, > > which messes up the indexing. > but if the splice is not at the end of the array it doesn't save > much. you still have to shift down multiple elements on each call to > splice. maybe you shift down fewer as there are now fewer elements up > top. anyhow, i was somewhat surprised to see splice was the fastest > method. i feel there is something odd and maybe with a larger data > set, that wouldn't be the case. > > uri > It's not about saving time. It's about removing a bug. In the code below, notice that there are two different outputs depending on the order that splice is applied. It's only by using descending indexing do you get the correct deletions. #!/usr/bin/env perl use strict; use warnings; say "ascending indexing"; my @a = 'a' .. 'z'; say "@a"; splice( @a, 3, 1 ); say "@a"; splice( @a, 9, 1 ); say "@a"; say "descending indexing"; @a = 'a' .. 'z'; say "@a"; splice( @a, 9, 1 ); say "@a"; splice( @a, 3, 1 ); say "@a"; __END__ ascending indexing a b c d e f g h i j k l m n o p q r s t u v w x y z a b c e f g h i j k l m n o p q r s t u v w x y z a b c e f g h i j l m n o p q r s t u v w x y z descending indexing a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i k l m n o p q r s t u v w x y z a b c e f g h i k l m n o p q r s t u v w x y z -- Don't stop where the ink does. Shawn H Corey -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/