http://www.perlmonks.org?node_id=1190641


in reply to printing every 2nd entry in a list backwards

use v5.16; use List::Util qw/pairmap/; # this is in core if you have a recent Per +l my @list = qw( 1 22 3 -4 5 666 7 ); say pairmap { "$b " } reverse @list;

Assuming you have the XS version of List::Util installed, this should blow away the grep/map solutions in terms of speed.

use v5.16; use List::Util qw/pairmap/; use Test::Modern qw( is_deeply is_fastest done_testing ); our @list = ( qw( 1 22 3 -4 5 666 7 ), 8 .. 99_999, ); my %implementations = ( pairmap => sub { no warnings; my @x = pairmap { $a } reverse @:: +list }, grepstate => sub { my @x = grep { state $i; $i++ % 2 +== 0 } reverse @::list }, grepmy => sub { my $i; my @x = grep +($i++ % 2 == 0), rev +erse @::list }, grepbit => sub { my $i; my @x = grep $i^=1, reverse @::lis +t }, mapmy => sub { my $i; my @x = map +($i++ & 1 ? () : $_), + reverse @::list }, mapidx => sub { my @x = map $::list[$#::list-$_*2] +, 0..$#::list/2 }, ); # Known good result my $reference = [ $implementations{pairmap}->() ]; for my $key (sort keys %implementations) { is_deeply( [ $implementations{$key}->() ], $reference, "$key produces correct output", ); } { local $Test::Modern::VERBOSE = 1; is_fastest('pairmap', -3, \%implementations); } done_testing; __END__ ok 1 - grepbit produces correct output ok 2 - grepmy produces correct output ok 3 - grepstate produces correct output ok 4 - mapidx produces correct output ok 5 - mapmy produces correct output ok 6 - pairmap produces correct output ok 7 - pairmap is fastest # pairmap - 3 wallclock secs ( 3.24 usr + 0.01 sys = 3.25 CPU) @ 17 +5.08/s (n=569) # grepbit - 3 wallclock secs ( 3.23 usr + 0.00 sys = 3.23 CPU) @ 10 +9.91/s (n=355) # mapidx - 3 wallclock secs ( 3.18 usr + 0.00 sys = 3.18 CPU) @ 77. +36/s (n=246) # mapmy - 3 wallclock secs ( 3.18 usr + 0.01 sys = 3.19 CPU) @ 76.1 +8/s (n=243) # grepmy - 3 wallclock secs ( 3.24 usr + 0.01 sys = 3.25 CPU) @ 68. +62/s (n=223) # grepstate - 3 wallclock secs ( 3.12 usr + 0.00 sys = 3.12 CPU) @ +33.33/s (n=104) ok 8 - no (unexpected) warnings (via done_testing) 1..8

UPDATE: Added the grep $i^=1, reverse solution, which is fast, but still loses to pairmap.