http://qs321.pair.com?node_id=1107894


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.