Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: replace a string multiple times

by Loops (Curate)
on Nov 15, 2014 at 11:25 UTC ( #1107301=note: print w/replies, xml ) Need Help??

in reply to replace a string multiple times

One way to do this is by putting what you're trying to repeat inside parentheses, and then use the $1 variable which will contain the matching contents:

$_ = "hint int stint"; s/(int)/$1$1$1/g; print;
hintintint intintint stintintint

The $& variable contains the contents of your entire match without using the parentheses even:

$_ = "hint int stint"; s/int/$&$&$&/g; print;

And prints the same thing but can have performance issues if you're using a version of Perl prior to version 5.20.

And in either case above, if you only want to match the entire word "int" and not when it's part of another word, use \b to designate a word boundary:

$_ = "hint int stint"; s/\b(int)\b/$1$1$1/g; print;
hint intintint stint

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2022-05-18 13:01 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (70 votes). Check out past polls.