Agreed. Combining the ability to call a subroute to do your bidding and back references makes for some very handy abilities.
For example:
Say I have a string:
"The %NOUN% can jump very %ADVERB%"
And say I have hash:
%wordBank = (
NOUN => "kangaroo",
ADVERB => "far",
)
I wanted to replace what is in the string with what is in the hash, so originally, I iterated through the hash and did a replace on the string as I found each hash key. This is terribly inefficient, so I reworked it to find items delimited by %..% in the string, and used the delimited keyword to directly call the value from the hash. This save me a lot of time, especially when %wordBank is very large.
#!/usr/bin/perl -w
use strict;
sub safeReplace {
my($hashkey,%hash) = @_;
my $hash = \%hash;
my $retval = '';
if (defined($hash{$hashkey})) {
$retval = $hash{$hashkey};
} else {
$retval = "\%$hashkey\%";
}
return $retval;
}
sub preProcessStr {
my($string,%options) = @_;
$string =~ s/%(.+?)%/safeReplace($1,%options)/ge;
return $string;
}
my %options = (
ARG1 => "test",
ARG2 => "123...",
);
my $string = 'Hello %ARG1%, counting down %ARG2% .. %NOT%';
$string = preProcessStr($string,%options);
print "$string\n"
|