Let me point out a couple notes on using regexes to solve this problem; first, though, using modulus is definitely the way to go (it averages between 3 and 2.5 times faster than regex approaches). It is important, when given a language such as Perl, to know which tools are hammers, screwdrivers, and wrenches; and even moreso, which problems are nails, screws, and bolts. This is a case where you are using a sledgehammer (a regex) to flatten a piece of wood, when a simple piece of sandpaper (the
% operator) will do.
There are four generic approaches to this:
- /(\d)*(\d)/
- useless capturing of preceeding digits; actually captures one digit at a time over and over again; useless backtracking is forced; 2.96 x slower than modulus
- /(\d*)(\d)/
- useless capturing of preceeding digits; useless backtracking is forced; 2.80 x slower than modulus
- /\d*(\d)/
- useless backtracking is forced; 2.79 x slower than modulus
- /(\d)$/
- optimized (goes to end of string automatically); 2.54 x slower than modulus
Code used for benchmarks:
use Benchmark 'timethese';
$x = int (1_000_000 * rand 1_000_000);
timethese(-5, {
multiple => sub { $x =~ /(\d)*(\d)/ },
backtrack_c => sub { $x =~ /(\d*)(\d)/ },
backtrack => sub { $x =~ /\d*(\d)/ },
opt => sub { $x =~ /(\d)$/ },
mod => sub { $x % 10 },
});
If
snafu doesn't mind, I'd like to use this as an example in
my book -- first to show how to craft a regex, then to show why there are some places where a regex is overkill.
japhy --
Perl and Regex Hacker
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.