6.9. Matching Shell Globs as Regular ExpressionsProblemYou want to allow users to specify matches using traditional shell wildcards, not full Perl regular expressions. Wildcards are easier to type than full regular expressions for simple cases. SolutionUse the following subroutine to convert four shell wildcard characters into their equivalent regular expression; all other characters will be quoted to render them literals. sub glob2pat { my $globstr = shift; my %patmap = ( '*' => '.*', '?' => '.', '[' => '[', ']' => ']', ); $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge; return '^' . $globstr . '$'; } Discussion
A Perl pattern is not the same as a shell wildcard pattern. The shell's
The function given in the Solution makes these conversions for you, following the standard wildcard rules used by the
In the shell, the rules are different. The entire pattern is implicitly anchored at the ends. A question mark maps into any character, an asterisk is any amount of anything, and brackets are character ranges. Everything else is normal.
Most shells do more than simple one-directory globbing. For instance, you can say See Also
Your system's
csh
(1) and
ksh
(1) manpages; the Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|