in reply to Converting a stringified regexp back into a regexp

For efficiency purposes, you might want to keep the non-stringified regexp inside the hash. In other words, changing:

$hash{"$regexp"} = $value; ... $value = $hash{$key}; $regexp = qx/$key/; # Expensive

to

$hash{"$regexp"} = [ $regexp, $value ]; ... $value = $hash{$key}[1]; $regexp = $hash{$key}[0];

That way, you won't have to recompile the regexp.

OR! If you can't change the hash's structure, keep the compiled regexp in a second hash:

$hash{"$regexp"} = $value; $regexps{"$regexp"} = $regexp; ... $value = $hash{$key}; $regexp = $regexps{$key};

Replies are listed 'Best First'.
Re^2: Converting a stringified regexp back into a regexp
by tlm (Prior) on Apr 07, 2005 at 14:52 UTC

    A variant of this idea would be to memoize qr:

    { my %cache; sub my_qr { $cache{ $_[0] } ||= qr/$_[0]/ } }
    though one loses some of the modifier syntax.

    the lowliest monk

Re^2: Converting a stringified regexp back into a regexp
by mirod (Canon) on Apr 07, 2005 at 14:51 UTC

    Indeed I only do the re-building of the regexp once, afterwards I keep a hash $hash{"$regexp"} = { regexp => $regexp, value => $value }; (actually it's handler instead of value, but you get the idea).

    update: sorry, I did not understand your comment I think. I _have_ to get the regexp passed as a string, in order to keep backwards compatibility. And as this is for XML::Twig, I don't think I can go about changing the code that uses it ;--(