in reply to How to make these reg exp changes?

Your solutions work OK - thanks to both of you!
But I have a question (maybe I should have written this before):
What I must change is:
....MMMMiiii => ooooMMMMiiii ....MMMMoooo => iiiiMMMMoooo iiiiMMMM.... => iiiiMMMMoooo ooooMMMM.... => ooooMMMMiiii
I mean, If you do not have some character before the '.' , how will it understand to replace for example, '.' with 'I' if I have 'O' after the string of 'M'? Is there any chance that this can be done?

Replies are listed 'Best First'.
Re^2: How to make these reg exp changes?
by ikegami (Patriarch) on Nov 15, 2009 at 23:39 UTC
    $ perl -wle' my %neg = ( o => "i", i => "o" ); while (<>) { chomp; s/([io])(M*)(\.+)/ $1.$2.( $neg{$1} x length($3) ) /eg; s/(\.+)(?=M*([io]))/ $neg{$2} x length($1) /eg; print; } ' ....MMMMiiii ....MMMMoooo iiiiMMMM.... ooooMMMM.... ooooMMMMiiii iiiiMMMMoooo iiiiMMMMoooo ooooMMMMiiii

    Simpler version that only works with Perl 5.10+:

    $ perl -wle' my %neg = ( o => "i", i => "o" ); while (<>) { chomp; s/([io])M*\K(\.+)/ $neg{$1} x length($2) /eg; s/(\.+)(?=M*([io]))/ $neg{$2} x length($1) /eg; print; } ' ....MMMMiiii ....MMMMoooo iiiiMMMM.... ooooMMMM.... ooooMMMMiiii iiiiMMMMoooo iiiiMMMMoooo ooooMMMMiiii

    I could have used -p above, but I wanted to make clear that %neg only needs to be initialized once without complicating the issue by adding a BEGIN. Here's the 5.10+ version using -p:

    perl -ple' BEGIN { %neg = qw( i o o i ) } s/([io])M*\K(\.+)/ $neg{$1} x length($2) /eg; s/(\.+)(?=M*([io]))/ $neg{$2} x length($1) /eg; '

    Update: Added \K version. \K rocks.
    Update: Added explanation about -p.

      exactly what I was looking for... The trick with the hash was just the thing!
      Thank you very much!
        Honestly, the hash has nothing to do with the problem.
        $neg{$1}
        is just short for
        ($1 eq 'o' ? 'i' : 'o')
        weird?
        $s='III...MMMMMOOOO....MMMIIII'; print $s."\n"; %neg = ( O => "I", I => "O" ); $s=~s/([IO])(M*)(\.+)/ $1.$2.( $neg{$1} x length($3) ) /eg; $s=~s/(\.+)(?=M*([IO]))/ $neg{$2} x length($1) /eg; print $s;print "\n"; <code> It prints:<br> <code> III...MMMMMOOOO....MMMIIII IIIOOOMMMMMOOOOIIIIMMMIIII