subroutine explanation

F

fred

I have some code created to takes some rules from external file and
apply these rules on text file. My perl experience is somewhat limited
and I was wondering if soneone on this group can give me an
explanation of it.

sub apply_rules {
my ($_txt, $_rules) = @_;
for (keys %{$_rules}) {
my $exp = $_;
$exp =~ s{\s}{\\s*}g;
my $re = $_rules->{$_};
my $rslt;
eval ("\$rslt = \$\$_txt =~ s{$exp}{$re}gis");
printf " >Replaced '$exp' %d times.\n", $rslt;
}
}
 
A

Anno Siegel

fred said:
I have some code created to takes some rules from external file and
apply these rules on text file. My perl experience is somewhat limited
and I was wondering if soneone on this group can give me an
explanation of it.

sub apply_rules {
my ($_txt, $_rules) = @_;
for (keys %{$_rules}) {
my $exp = $_;
$exp =~ s{\s}{\\s*}g;
my $re = $_rules->{$_};
my $rslt;
eval ("\$rslt = \$\$_txt =~ s{$exp}{$re}gis");
printf " >Replaced '$exp' %d times.\n", $rslt;
}
}

$_rules is a (reference to) a hash that contains pairs consisting of a
pattern and a replacement. $_txt is a reference to some text. Basically,
the pattern is replaced with the replacement everywhere it matches
(case-insensitively) in the text. This happens for every pair in the hash.
Why the author thought "eval" was needed to achieve this isn't obvious,

$rslt = $$_txt =~ s{$exp}{$re}gis;

would do the same thing.

Before application, each pattern is pre-processed to replace blanks with
"\s*", which means that when the pattern indicates a single blank, any
sequence of white space will match. That includes no whitespace at all,
wonder if that's right.

After each pattern/replacement pair in the hash, the pattern is shown
along with the number of replacements that happened.

The effect of the routine is not well defined if the order of replacements
matters (if there are re-replacements), because the order of a hash
isn't well defined.

Anno
 

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,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top