This solution is non-destructive and uses an array slice rather than push'ing, pop'ing and shift'ing.
use strict;
use warnings;
my @array = qw{ ace big cat dog egg fig gog hog };
my @newArray = @array[ reOrder( scalar @array ) ];
print qq{@newArray\n};
sub reOrder
{
my $length = shift;
die qq{Array length not a multiple of 4\n}
if $length % 4;
my $low = 0;
my $high = $length - 1;
return
map { $_ % 2 ? ( $high --, $low ++) : ( $low ++, $high --) }
1 .. $length / 2;
}
The output.
hog ace big gog fig cat dog egg
Cheers, JohnGG
Update: Re-factored subroutine to handle any length of array.
sub reOrder
{
my $length = shift;
my $low = 0;
my $high = $length - 1;
my @slice =
map { $_ % 2 ? ( $high --, $low ++) : ( $low ++, $high --) }
1 .. $length / 2;
return @slice, $low == $high ? $low : ();
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|