subroutine explanation

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

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 %) {
    my $exp = $_;
    $exp =~ sg;
    my $re = $_rules->;
    my $rslt;
    eval ("$rslt = $$_txt =~ sgis");
    printf "  >Replaced '$exp' %d times.\n", $rslt;

Re: subroutine explanation

Quoted text here. Click to load it

$_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 =~ sgis;

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.


Site Timeline