Just for fun, I'm very new to Perl and I'm trying to write a simple text processing tool, but I'm stuck in a simple thing. The rules of the tool, read from a simple text file (not from the script, and that's probably the crucial thing), are a simple array of pattern/replace pairs to process a text file (like process each rule for each line). Here's the sub to apply transformations:
my ($text, @rules) = @_;
my @lines = split(/\n/, $text);
foreach ( @rules ) {
my $pattern = $_->{"pattern"};
my $replace = $_->{"replace"};
$lines = map {
$_ =~ s/$pattern/$replace/g;
} @lines;
}
return join("\n", @lines);
For instance, if there's a rule like pattern=[aeiou]
+ replace=*
, then text Foo bar
is processed into F** b*r
. That's what I want.
However I can't see why I can't use capture groups to replace text content. Let's say, pattern=([fF])
+ replace=<$1>
results into <$1>oo bar
, but I'm expecting <F>oo bar
. I guess I'm missing a very simple thing. What am I missing?
UPDATE:
After some experiments my finish result is:
sub escapeSubstLiteral {
my ($literal) = @_;
$literal =~ s/\//\\\//g;
$literal;
}
sub subst {
my ($pattern, $replace, $modifiers) = @_;
$modifiers ||= '';
my $expression = '$text =~ s/' . escapeSubstLiteral($pattern) . '/' . escapeSubstLiteral($replace) . '/' . $modifiers;
return sub {
my ($text) = @_;
eval $expression;
$text;
};
}
$customSubst = subst($pattern, $replace, $modifiersToken);
$foo = $customSubst->($foo);
$bar = $customSubst->($bar);