Daniel Kaplan
Daniel Kaplan

Reputation: 721

Can I get the results from a regex into a new string?

I already know how to use regex to modify a string, i.e.

$string1 =~ s/[aeiouy]//gi;

But what's the syntax to keep the original string? i.e.

$string2 = $string1 = s/[aeiouy]//gi;

So that $string1 is the before and $string2 is the after.

Am sure there is a way, thanks for your help

Upvotes: 0

Views: 36

Answers (1)

mob
mob

Reputation: 118605

A way, if you have Perl 5.14 or better, is with the /r modifier.

$string1 = "cat toy";
$string2 = ($string1 =~ s/[aeiouy]//gir);
print $string1;       # "cat toy", unchanged
print $string2;       # "ct t",    with modifications

It works with the transliteration operator, too

$string1 = "cat toy";
$string2 = ($string1 =~ tr/aeiouy/123456/r);
print $string1;       # "cat toy"
print $string2;       # "c1t t46"

Upvotes: 1

Related Questions