A string is a regular expression of sorts, so you could
simply extract these from a hash and test against them.
However, each time through you will have to recompile the
pattern, which can be slow going if you do this a lot.
Using the
qr operator can help a bit, or using the /o
switch to prevent compilation, but you might be better
off using a hash of subs which just happen to contain
regular expressions.
Here's something that demonstrates my idea:
my %validate = (
int => sub { my($v)=@_; $v=~/^[0-9]+$/; },
date => sub { my($v)=@_; $v=~/^[12]\d\d\d\-[01]?\d\-[0123]?\d/
+; },
);
foreach my $value (qw [ 24 140 510 2001-04-14 3014-30-55 ])
{
print "$value\n";
foreach my $type (sort keys %validate)
{
print "\tIs '$type'\n" if ($validate{$type}($value));
}
}
If you have many, many different patterns to define, you might
want to
eval them into the hash, like so:
$validate{$new_type}
= eval "sub { my(\$v)=\@_; \$v=~$regex; }";
Of course, taking special care to ensure $regex
was a self-contained regex (i.e.
/x/ or
!/!) and did not contain anything that was
going to be invalid when eval'd, though of course you can
always check $@ and see what went wrong.
The advantage to using a full sub over just a regex is that
you can validate in a context outside of a regex just to be
sure. For example, you could check that the day of the month
was actually 31 or less, instead of possibly 39.
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.