Corion's approach is better than this (building and applying a single list of indexes is less work than repeated array mutations), but the reverse/splice dance you had in mind might look something like this:
use Modern::Perl; use Test::More; main(); sub main { my @foo = (1 .. 8); my @bar = reverseswap( @foo ); is $bar[0], 2, 'swapped the first one'; is $bar[1], 1, '... with the second'; is $bar[2], 4, '... and so on'; is $bar[3], 3, '... and so on'; is $bar[4], 6, '... and so on'; is $bar[5], 5, '... and so on'; is $bar[6], 8, '... and so on'; is $bar[7], 7, '... and so on'; done_testing; } sub reverseswap { my @array; push @array, reverse splice @_, 0, 2 while @_; return @array; }
In reply to Re: Switch the odd/even elements of an array
by chromatic
in thread Switch the odd/even elements of an array
by jaredor
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |