Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: hashes in regexes

by bjelli (Pilgrim)
on Mar 29, 2001 at 05:26 UTC ( #68021=note: print w/replies, xml ) Need Help??


in reply to hashes in regexes

As a lowly acolyte I have great respect for <kbd>map</kbd> and a fondness of good old <kbd>foreach</kbd>. So I naturally thought: isn't a loop with simple pattens faster than a pattern with <kbd>|</kbd> in it?

Here's my benchmarking code:

use Benchmark; timethese(500, { 'or pattern' => \&orpattern, 'many patterns' => \&manypatterns }); sub init { %sub_hash = (John => Mike, Jack => Mark, Joe => Moe); $string = "Dear John!.\nI've run off with Jack and Joe.\nSue\n\n" x 1000; } sub orpattern { init; my $keys = join '|', map "\Q$_\E", keys %sub_hash; my $keys_REx = qr/$keys/; $string =~ s/($keys_REx)/$sub_hash{$1}/g; return $string; } sub manypatterns { init; my %patterns = map { qr/$_/ => $sub_hash{$_} } keys %sub_hash; foreach $pat (keys %patterns) { my $replace = $patterns{$pat}; $string =~ s/$pat/$replace/g; } return $string; }

And the results:

Benchmark: timing 500 iterations of many patterns, or pattern...
many patterns:  2 wallclock secs ( 1.61 usr +  0.00 sys =  1.61 CPU)
or pattern: 12 wallclock secs (11.94 usr +  0.01 sys = 11.95 CPU)

Of course there's a difference in functionality between the two, just think of:

%substitute_hash = ( Jack => Chris, Chris => Jaquline );
--
Brigitte    'I never met a chocolate I didnt like'    Jellinek
http://www.horus.com/~bjelli/         http://perlwelt.horus.at

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://68021]
help
Chatterbox?
[mz2255]: Yes, just edited the scratchpad. Not sure if I'm doing something wrong, it's my first time.
[ambrus]: No, you're not doing anything wrong. It's just that our automatic spam filters confuse you with the spammers who post advertisments for online shops of counterfeit branded clothing.
[ambrus]: Or unless you left the title field empty or entered a very short title for the node, but then you'd get a message saying that.
[ambrus]: I hope Corion or some other admin is here and can check the logs to see what the problem is.
[mz2255]: I wish I had an online shop but sadly no. The title field definitly wasn't short, had a perl module in the title with 5-6 additional words.

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (12)
As of 2017-10-19 15:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My fridge is mostly full of:

















    Results (255 votes). Check out past polls.

    Notices?