in reply to Re: how do I use s///e
in thread how do I use s///e

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"

Replies are listed 'Best First'.
Re: Re: Re: how do I use s///e
by revdiablo (Prior) on Jan 26, 2004 at 20:37 UTC

    I realize your code was mainly for demonstration purposes, but it can be shortened considerably. I'm sure this can be golfed down even more, but I came up with the following snippet, which I feel is simple yet not too obfuscated (and also demonstrates the use of s///e, so I guess it's not really too OT):

    #!/usr/bin/perl use strict; use warnings; my $str = 'The %NOUN% can jump very %ADVERB% with his %APPENDAGES%'; my %wb = ( NOUN => "kangaroo", ADVERB => "far", ); $str =~ s/%([^%]+)%/$wb{$1} || "\%$1\%"/ge; print "$str\n";

    Update: %s/\$template/\$str/g; silly mistake caused by last-minute-edits-without-testing. Thanks to Not_a_Number for the catch.

      Thanks :)