The subroutine glob2pat from the Perl Cookbook is well known and often quoted (including a couple of nodes here), but I've just used it for the first time. I find it hard to belive that I'm the first person to find a bug in it. SuperSearch on glob2pat didn't show the bug, and neither did Google.
[0-9] gets converted to
^[0\-9]$.
In other words it does not convert a range correctly since the hyphen is escaped. It is the
\Q wot does it. My solution is simple:
sub glob2pat {
my $globstr = shift;
my %patmap = (
'*' => '.*',
'?' => '.',
'[' => '[',
']' => ']',
'-' => '-', # Added by me
);
$globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
return '^' . $globstr . '$';
}
Or am I wrong? This really puzzles me, because it has been around for so long.
Update: I have since realised that neither the original code or my "solution" copes with
any escaped characters, like \?, \[, or \*. To make matters worse these characters inside [] should not be converted at all, but they get converted regardless.
Update 2: The following solves the escaped characters, but still does not solve ? and * inside [] which should not be translated:
$globstr =~ s{(?:^|(?<=[^\\]))(.)} { $patmap{$1} || "\Q$1" }ge;
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.