Is it possible to specify the maximum number of matches to replace. For instance if matching 'l' in "Hello World", would it be possible to replace the first 2 'l' characters, but not the third without looping?
$str = "Hello world!";
$str =~ s/l/r/ for (1,2);
print $str;
I don't see what's so bad about looping.
Actually, here's a way:
$str="Hello world!";
$str =~ s/l/$i++ >= 2 ? "l": "r"/eg;
print $str;
It's a loop, of sorts, since s///g works in a loopy way when you do this. But not a traditional loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With