Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Tips on how to perform this substitution?

by moritz (Cardinal)
on Jan 22, 2014 at 13:30 UTC ( [id://1071611]=note: print w/replies, xml ) Need Help??


in reply to Tips on how to perform this substitution?

The trick with the alternation is that your regex matches -s delimited by B's, thus slurping them up. The next regex search starts off after the last B, and needs to skip the following -s to find the next B.

use 5.010; use strict; use warnings; $_ = '------BBBBB----------------------------------------------------- +-------------------------------------------------------BBBBBB----BBBB +BBBB-----------------BBBBBB------------------------------------------ +--------------BBBBBBB---------------BBBBB-----BBBBBBBBB-------------- +----------------------BBBBBBBBB------BBBBBBBBB----------------------- +-----BBBBBBBBB--------------------------------------BBBBBBBB-------BB +BBBB---------------------BBBBBBB--------------------------BBBBBBBB--- +-'; my $expected = 'iiiiiiMMMMMooooooooooooooooooooooooooooooooooooooooooo +oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooMMMM +MMiiiiMMMMMMMMoooooooooooooooooMMMMMMiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii +iiiiiiiiiiiiiiiiiiiiiiiiMMMMMMMoooooooooooooooMMMMMiiiiiMMMMMMMMMoooo +ooooooooooooooooooooooooooooooooMMMMMMMMMiiiiiiMMMMMMMMMooooooooooooo +oooooooooooooooMMMMMMMMMiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiMMMMMMM +MoooooooMMMMMMiiiiiiiiiiiiiiiiiiiiiMMMMMMMooooooooooooooooooooooooooM +MMMMMMMiiii'; s/(^|B+)(-+)($|B+)/ $1 . ("i" x length($2)) . $3/eg; s/-/o/g; s/B/M/g; say $expected; say $_; say $expected eq $_ ? 'yes' : 'no';

Replies are listed 'Best First'.
Re^2: Tips on how to perform this substitution?
by tobyink (Canon) on Jan 22, 2014 at 14:16 UTC

    It can be done in one s/// operation...

    use v5.10; use strict; use warnings; $_ = '--BBB----BB--B-------B--B--BBBB---B--'; s ((B+|.)) { state $char = 'i'; if (index($1, 'B') == 0) { $char = $char eq 'i' ? 'o' : 'i'; 'M' x length($1); } else { $char; } }eg; say;
    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

      That is way too complex :)

      my $p = "--BBB----BB--B-------B--B--BBBB---B--"; my @x = qw( i o ); my $x = 0; $p =~ y/B/M/; $p =~ s/(-+)/$x[$x++%2]x length($1)/ge; say $p;

      Enjoy, Have FUN! H.Merijn
Re^2: Tips on how to perform this substitution?
by Anonymous Monk on Jan 22, 2014 at 13:41 UTC
    Thank you very much for your kind tips!
    Will look at them carefully!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1071611]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (6)
As of 2024-04-23 21:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found