in reply to What is the best solution to swap input data?
GrandFather's solution is the most appropriate one I can think of, but there's something about (.)(.) that bugs me. ...no, not for any good reason. ;)
So here's an inferior solution that doesn't annoy me with (.)(.) (those beady eyes).
my $data = '123456789'; $data =~ s/(.{2})/reverse $1/eg; print $data, "\n";
You didn't define what happens if the string has an uneven number of characters. The most likely alternative is to do nothing with that extra digit at the end. ...but maybe you would prefer doing nothing with the leading digit, in the case of an uneven number of digits, or maybe you'd prefer to fail altogether. ...just some things to consider...
In case you're wondering why this solution is inferior, here's a small list:
Update:
The OP's original solution used substr, and since I was in the mood to tinker, I decided to work up my own substr version:
use strict; use warnings; my $data = '123456789'; my $output = ''; my $position = 0; while ( $position < length $data ) { $output .= reverse substr $data, $position, 2; $position += 2; } print $output, "\n";
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: What is the best solution to swap input data?
by Anonymous Monk on Nov 09, 2006 at 15:04 UTC | |
by Hofmator (Curate) on Nov 09, 2006 at 15:20 UTC |