Hi perlmonks,
I've been successfully (?) getting into Perl but now I'm a little stuck here.
Many times I found great solutions from you guys so I decided to register and make a thread myself now.
Say I got a string 'x x x a x x x b x x x a x x x b x x x' and want to replace all 'a's with a 'b' and all 'b's with an 'a'.
What's the best way of achieving this without making it replace a previously replaced 'a' (that now is a 'b') with an 'a'?
Here are my several ways I came up with, one of them fails due to the issue described above:
#!/usr/bin/env perl
use strict;
use warnings;
my $test = 'x x x a x x x b x x x a x x x b x x x';
print "ORIGINAL: $test\n\n";
# 1 - array
my @array = split(/ /, $test);
for (@array) {
if ($_ eq 'a') { $_ = 'b'; }
elsif ($_ eq 'b') { $_ = 'a'; }
}
print "ARRAY: @array\n";
# 2 - s/// (FAILS)
my $s = $test;
$s =~ s/a/b/g;
$s =~ s/b/a/g;
print "s///: $s\n";
# 3 - s/// map
my $map = join(' ', map{ if (/a/) { s/a/b/; } elsif (/b/) { s/b/a/; }
+$_ } split(/ /, $test));
print "s/// MAP: $map\n";
# 4 - substr
my $substr = $test;
for (my $i = 0; $i <= length($substr); $i++) {
if (substr($substr, $i, 1) eq 'a') { substr($substr, $i, 1) = 'b';
+}
elsif (substr($substr, $i, 1) eq 'b') { substr($substr, $i, 1) = 'a
+'; }
}
print "SUBSTR: $substr\n";
Output:
ORIGINAL: x x x a x x x b x x x a x x x b x x x
ARRAY: x x x b x x x a x x x b x x x a x x x
s///: x x x a x x x a x x x a x x x a x x x
s/// MAP: x x x b x x x a x x x b x x x a x x x
SUBSTR: x x x b x x x a x x x b x x x a x x x
Is there any way to achieve this with a single s/// operation?
Thanks for any suggestions that will all be greatly appreciated!
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.