First, I added the beginning and end of line anchors (^$). Your script would have determined that "123a123" was "alphabetic". That may be what you want, but I suspect not. Further, if it wasn't alphabetic, everything else would have resulted in "numeric", including something like "#$*&%(*&@", which is again probably something you don't want.#!/usr/bin/perl -w my $a = "aBcdeFG"; if ($a =~ /^[a-z]+$/i) { print "Alphabet\n"; } elsif ($a =~ /^\d+$/ ) { print "Numeric\n"; } else { print "Neither\n"; }
Incidentally, such regular expressions are how alphabetic and numeric data is identified. With regular expressions, there is really no need for special functions to test for these. If you must have them, you can write something like the following:
Cheers,sub IsNumeric { my $val = shift; if ( defined $val ) { return $val =~ /^\d+$/ ? 1 : 0; } else { warn "IsNumeric requires an argument!"; } }
Update: Sheesh. Trimbach totally beat me to the punch there and said exactly the same thing. Sigh.
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
In reply to (Ovid) Re: isAlpha / isNumeric
by Ovid
in thread isAlpha / isNumeric
by Jamnet
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |