in reply to Re: Chaining string ops
in thread Chaining string ops

You can get rid of the loop in your second example entirely.
my %subst_for = ( "walked" => "fed", "boy" => "girl", "dog" => "Audrey II" ); $_ = "the boy walked the dog"; my $alt = join '|', map quotemeta, keys %subs; s/($alt)/$subst_for{$1}/g;

Makeshifts last the longest.

Replies are listed 'Best First'.
Re: Re^2: Chaining string ops
by davido (Cardinal) on Aug 28, 2003 at 18:24 UTC
    Yes, you can do that, which creates a potentially huge alternation list for the regexp engine to swollow. I'm not sure that would be more efficient though, neither is it as clear.

    Alternation is a convenient tool inside a regexp, and I'm glad to see an example of how to make it work in the context of substituting multiple items with multiple substitute items.

    But alternation is also very inefficient, and can lead to a lot of backtracking even in relatively simple regular expressions. In that context, a loop may be more time efficient. Only benchmarking could say for sure.

    Dave

    "If I had my life to do over again, I'd be a plumber." -- Albert Einstein

      Yes, you can do that, which creates a potentially huge alternation list for the regexp engine to swollow. I'm not sure that would be more efficient though, neither is it as clear.

      Regex::PreSuf to the rescue!! It'll fix your efficiency problem, although it won't do much for readability :)
      --
      Mike