Tuesday, June 19, 2012

Extracting alternate items from an array in Perl

Hmm.. I forgot which web page I referred to, but this is a 2-liner code to extract the odd-th numbered items, or even-th numbered items in an array. :)




use Data::Dumper;$Data::Dumper::Indent = 3;


@array = ( 1, 2, 3, 4, 5, 6, 7 );


$flag = 0;
@oddth = grep {$flag ^= 1} @array;


print Dumper(\@oddth);
print "\n";


$flag = 1;
@eventh = grep {$flag ^= 1} @array;


print Dumper(\@eventh);
print "\n";



output :



No comments:

Post a Comment