in reply to What is the best solution to swap input data?
You can also do this with split, although my implementation is not quite optimal.
#!/usr/bin/perl use strict; use warnings; while(<DATA>){ chomp; my $in = $_; my @pairs = split(/(.{2})/); $_ = reverse foreach @pairs; my $out = join('', @pairs); print "in: $in => out: $out\n"; } __DATA__ 12345678 1234 12 1234 123456 87654321
Outputs:
in: 12345678 => out: 21436587 in: 1234 => out: 2143 in: 12 => out: 21 in: 1234 => out: 2143 in: 123456 => out: 214365 in: 87654321 => out: 78563412
As I said, I'm quite sure that this is far from optimal, as the regex is probably quicker, shorter, and at least as clear.
emc
At that time [1909] the chief engineer was almost always the chief test pilot as well. That had the fortunate result of eliminating poor engineering early in aviation.
—Igor Sikorsky, reported in AOPA Pilot magazine February 2003.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: What is the best solution to swap input data?
by johngg (Canon) on Nov 09, 2006 at 23:22 UTC | |
by swampyankee (Parson) on Nov 10, 2006 at 16:43 UTC |