|Welcome to the Monastery|
Switch the odd/even elements of an arrayby jaredor (Curate)
|on Mar 04, 2011 at 20:04 UTC||Need Help??|
jaredor has asked for the
wisdom of the Perl Monks concerning the following question:
I'm looking for a perl idiom for switching adjacent array elements with each other, e.g., to go from1 2 3 4 5 6 7 8
to2 1 4 3 6 5 8 7
Every way that I've done this before has been rather grotty. My main interest is in having something that avoids using indexing; this is not only for personal preference, but also because my fellow users will also have to maintain what I give them and these users don't "do" indexing well. (Heck, *I* don't do indexing well.)
The main constraint is that order is important; these are Y,X pairs being transformed into X,Y pairs, and these pairs have to maintain relative order. Thus the naked reverse() call would not be appropriate. However, it is checked beforehand that there is an even number of elements in the array, so a clever use of reverse() might work.... Also there is no uniqueness for the Y values, so transforming to a hash and back has even more potential pitfalls than reverse().
And there is a second constraint: No CPAN. The corporate IT support for perl is "perl only" and is always a few years out-of-date. Thus natatime() is out of consideration :-(
A simple example of code that I currently write would be something like
But I can't help feeling that there is some perlism using reverse() and/or splice() and/or shift() and/or ??? that would be more in line with the concept of a whole array function. My Google-fu let me down and I'm in enough of a pique to ask this question even though I know that most people would tell me I have an acceptable method at hand.
Apologies: The above code snippet is untested since I am writing this on a machine with no perl installed.
Your grateful novice