Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: need a regular exdpression in perl

by Loops (Curate)
on Nov 20, 2014 at 08:24 UTC ( #1107894=note: print w/replies, xml ) Need Help??


in reply to need a regular exdpression in perl

Your source string needs to be in single quotes, otherwise Perl will try to interpolate '@begin' and '@end' as arrays. You also don't want to put your replacement strings inside square brackets, that groups them as a single array reference inside of @replace, rather than as individual strings.

Anyway, this should get you started:

use strict; use warnings; my $string=' hi hello @begintobe replace @end asas x x x x x zxzxax hi hello hi hellooo @beginthis has tobe replaced @end ...'; my @replace= ("replacestring1","replacestring2"); $string =~ s|\@begin.*?\@end |shift @replace // '[null]' |sexg; print $string;

Usually regular expression substitutions are written as:

s/<pattern>/<substitution text>/<modifiers>

But in my code above, the vertical bar (or pipe) symbol (|) is used instead. It's also split over 3 lines which is allowed when you use the "x" modifier.

The "e" modifier means that instead of substitution text, the given code will be executed for each @begin ... @end match. The code shown, removes the first element of the array and returns it for the current substitution. If the @array becomes empty, the literal value '[null]' will be used instead.

The "g" modifier causes the substitution to be done as many times as there are matches found in the string -- consuming another array element each time. Without it only the first substitution would be done.

And lastly the "s" modifier means that the period character in the pattern, will match newline characters since those appear in your example input string.

Much more information can be found in the perlre and perlretut documentation.

Replies are listed 'Best First'.
Re^2: need a regular exdpression in perl
by Corion (Pope) on Nov 20, 2014 at 08:31 UTC

    Slightly off-topic, but when writing such a templating engine, I prefer to deal with missing replacement values by leaving the template parameters as-is (that is, replacing the template parameter by itself instead of a (missing) value):

    $string =~ s|(\@begin.*?\@end) |shift @replace // 'Missing parameter for ' . $1 |sexg;

    I find this helps me debug the template better, as I easily see which template expression failed. This still does not help me see why a value was missing, but at least I know where the value was missing.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (1)
As of 2021-04-17 04:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?