in reply to Regex question

Why are you using a regex to check a one-character value?

if( $vartocheck eq lc($firstchar) ) { ++$foo; }

Update: The benchmark is mightier than the word:

#! /usr/bin/perl -w use strict; use Benchmark; use vars qw/$vartocheck $firstchar/; $vartocheck = 'x'; $firstchar = 'y'; my $iters = shift || 10000; timethese $iters, { 'eq !=' => sub { return $vartocheck eq lc($firstchar) }, 're !=' => sub { return $vartocheck =~ /\Q$firstchar\E/i }, }; $firstchar = 'x'; timethese $iters, { 'eq ==' => sub { return $vartocheck ne lc($firstchar) }, 're ==' => sub { return $vartocheck !~ /\Q$firstchar\E/i }, }; __END__ % perl eqre 10000000 Benchmark: timing 10000000 iterations of eq !=, re !=... eq !=: 8 wallclock secs ( 8.00 usr + 0.02 sys = 8.02 CPU) @ 12 +46882.79/s (n=10000000) re !=: 14 wallclock secs (13.74 usr + 0.10 sys = 13.84 CPU) @ 72 +2543.35/s (n=10000000) Benchmark: timing 10000000 iterations of eq ==, re ==... eq ==: 8 wallclock secs ( 6.98 usr + 0.04 sys = 7.02 CPU) @ 14 +24501.42/s (n=10000000) re ==: 17 wallclock secs (16.76 usr + -0.01 sys = 16.75 CPU) @ 59 +7014.93/s (n=10000000)

Update: Taking tye's advice below to heart, I anchored the regex, even though that was not the case in the initial question. It is interesting to note that the results for the regex are worse than before. The only other thing to check would be to use lexicals instead of package variables. This, of course, is left as an exercise to the reader.

timethese $iters, { 'eq !=' => sub { return $vartocheck eq lc($firstchar) }, 're !=' => sub { return $vartocheck =~ /^\Q$firstchar\E$/i }, }; __END__ % perl eqre 10000000 Benchmark: timing 10000000 iterations of eq !=, re !=... eq !=: 7 wallclock secs ( 7.42 usr + 0.00 sys = 7.42 CPU) @ 13 +47708.89/s (n=10000000) re !=: 26 wallclock secs (25.89 usr + 0.01 sys = 25.90 CPU) @ 38 +6100.39/s (n=10000000) Benchmark: timing 10000000 iterations of eq ==, re ==... eq ==: 8 wallclock secs ( 6.60 usr + 0.00 sys = 6.60 CPU) @ 15 +15151.52/s (n=10000000) re ==: 27 wallclock secs (27.77 usr + 0.00 sys = 27.77 CPU) @ 36 +0100.83/s (n=10000000)

--
g r i n d e r

Replies are listed 'Best First'.
(tye)Re: Regex question
by tye (Sage) on May 29, 2001 at 18:49 UTC

    An unanchored regex is much more like index than eq, BTW.

            - tye (but my friends call me "Tye")