perl read the regular expression from a filere
Howdie
I 've classified all the regular expressions I used the most as library files. To give a dummy example, I have a file called /mysdk/library/regex/email/match
with the contents:
^[a-z]@[a-z]\.com$
(I know this is not the good regex, but that's for the example :)). And I have a lot of folders with commonly used regular expressions:
/library
/regex
/email
/url
开发者_如何转开发 /social_security
...
Now I'm doing a Perl script that will tell me if a given string matches a given regular expression from my library. For example,
perl my-script.pl email john@example.com
And the script should print 0 on false and 1 on true. But it does not work :( This my script:
if($ARGV[1])
{
if(open(REGEX_CONSTANT,"/mysdk/library/regex/$ARGV[0]/match"))
{
$regex_constant=<REGEX_CONSTANT>;
close(REGEX_CONSTANT);
if($ARGV[1] =~ m/$regex_constant/) { print 1; exit }
}
print 0
}
else
{
print 0
}
I've also tried
if($ARGV[1] =~ m/($regex_constant)/) { print 1; exit }
Even when the string is supposed to match, it prints 0. I know it finds the file and successfully reads the content from it because I've debugged that. What am I doing wrong?
It's possible you have trailing newlines on those, or maybe headers. Try running chomp on the strings you read in. Hard to tell without know what the files look like.
Have you considered looking at Regexp::Common
This might not solve your problem directly, but could help you classify and its already includes some very common regex's you may find useful.
Rather than putting the regular expressions in files, you might consider putting them in a module:
# In FavoriteRegex.pm.
package FavoriteRegex;
use strict;
use warnings;
use parent qw(Exporter);
our @EXPORT = qw();
our @EXPORT_OK = qw(%FAVS);
our %FAVS = (
foo => qr/foo/,
integer => qr/\A\d+\Z/,
);
1;
Scripts that need those regular expressions become much simpler:
# In some_script.pl.
use strict;
use warnings;
use FavoriteRegex qw(%FAVS);
say 'foo' if 'blah foo blah' =~ $FAVS{foo};
say 'integer' if '1234' =~ $FAVS{integer};
say 'integer?!?' if '1234.0' =~ $FAVS{integer};
Even if your project requires that the regular expressions to live in their own non-Perl files, the work of reading those files should be done in the module (FavoriteRegex.pm
in this example), not the scripts.
精彩评论