Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

RE: RE: RE: Selective substitution: not in Perl?

by atl (Pilgrim)
on Aug 16, 2000 at 15:27 UTC ( #28095=note: print w/replies, xml ) Need Help??


in reply to RE: RE: Selective substitution: not in Perl?
in thread Selective substitution: not in Perl?

Black magic! I'm really impressed, I didn' know you can put that all into the substitution pattern. /me bows to Nuance ...

As for my solution, I was focused on the sample input given, I didn't think of the more general problem. But you're right about this.

As for your script, it works with a small alteration:

$string =~ s/($pattern)/$i++ == $n ? $better : $1/ge;
If you increment $i in a seperate statement, the whole block evaluates to the value of $i und you get
abacab 0b1c2b
Ok, now we're having fun :-)...

Andreas (waiting for the chinese food delivery service ...)

Replies are listed 'Best First'.
RE: RE: RE: RE: Selective substitution: not in Perl?
by merlyn (Sage) on Aug 16, 2000 at 15:33 UTC
    To make it even clearer, remember that the right side of the s///ge can be an arbitrary block. Here's the "Perl Bowling" style written for clarity:
    { my $count = 0; $string =~ s{($pattern)}{ my $source = $1; $count++; if ($count == $target) { $source = $replacement; # replace! } $source; # either original or replacement now }ge; };
    And yes, you can actually write it like that, just as you see. If you're doing anything odd in the right hand side in a s///e, I recommend expanding it out like that.

    -- Randal L. Schwartz, Perl hacker

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2022-05-24 02:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (82 votes). Check out past polls.

    Notices?