Multiple regex operations

O

Orion Mímameiðr

Is there a way to apple multiple regex operations to a single string
without writing them all out?

example.

suppose I have some variable $var and want it apple three regexs to
it. is there a faster way than

$var =~ s/foo/bar/;
$var =~ s/foo/bar/;
$var =~ s/foo/bar/;
 
J

Jürgen Exner

Orion Mímameiðr said:
Is there a way to apple multiple regex operations to a single string
without writing them all out?

Regular expressions are expessions, not operations.
example.

suppose I have some variable $var and want it apple three regexs to
it. is there a faster way than

You don't "apply" a regular expression. Well, unless you are talking
about matches/doesn't match.
$var =~ s/foo/bar/;
$var =~ s/foo/bar/;
$var =~ s/foo/bar/;

If it has to be exactly three times you can do a simple loop:

for my $x (1..3) {
$var =~ s/foo/bar/;
}

If you want to do it for all 'foo' in a string then use the g modifier:
$var =~ s/foo/bar/g;

jue
 
J

Justin C

Is there a way to apple multiple regex operations to a single string
without writing them all out?

example.

suppose I have some variable $var and want it apple three regexs to
it. is there a faster way than

$var =~ s/foo/bar/;
$var =~ s/foo/bar/;
$var =~ s/foo/bar/;

my $var = "To make foo you will need orange and whisky.\n";

my @old = qw/foo orange whisky/;
my @new = qw/bar lemon gin/;

print $var;
foreach my $old (@old) {
my $new = shift (@new);
$var =~ s/$old/$new/;
}
print $var;

Though this only becomes less to type when you have more @old and @new.

TMTOWTDI.

Justin.
 
D

Dr.Ruud

Orion said:
Is there a way to apple multiple regex operations to a single string
without writing them all out?

example.

suppose I have some variable $var and want it apple three regexs to
it. is there a faster way than

$var =~ s/foo/bar/;
$var =~ s/foo/bar/;
$var =~ s/foo/bar/;

perl -Mstrict -wle '
{ my $qr= 2;
my @qr= ( qr/\s+\z/, qr/\A\s+/, qr/\s+/ );
sub qr {
$qr= ( $qr + 1 ) % 3;
if ( $qr == 2 ) { s/$qr[$qr]/ /g } else { s/$qr[$qr]// }
}
}

my $s = " abc \t def \n ghi ";

for ( "apple" .. "apply" ) {
&qr for $s;
}
print "<$s>";
'
<abc def ghi>
 
C

C.DeRykus

Is there a way to apple multiple regex operations to a single string
without writing them all out?

example.

suppose I have some variable $var and want it apple three regexs to
it. is there a faster way than

$var =~ s/foo/bar/;
$var =~ s/foo/bar/;
$var =~ s/foo/bar/;


$var =~ s/foo/bar/ for 1..3;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top