Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a value is numeric, alphabetical or alphanumeric in Perl?

Tags:

regex

perl

I have array which values are user input like:

aa df rrr5 4323 54 hjy 10 gj @fgf %d

Now I want to check each value in array to see whether it's numeric, alphabetic (a-zA-Z), or alphanumeric and save them in other respective arrays.

I have done:

my @num;
my @char;
my @alphanum;

my $str =<>;
  my @temp = split(" ",$str);
        foreach (@temp)
           {
                print "input : $_ \n";
                if ($_ =~/^(\d+\.?\d*|\.\d+)$/)
                    {
                        push(@num,$_);
                    }
           }

This works. Similarly I want to check for alphabet, and alphanumeric values

Alphanumeric example are: fr43 6t$ $eed5 *jh

like image 236
dexter Avatar asked Feb 03 '26 18:02

dexter


1 Answers

Perl supports POSIX character classes, so you can actually do this:

$string =~ /^[[:alpha:]]+$/;
$string =~ /^[[:alnum:]]+$/;

Numbers are less well defined, but Scalar::Util's looks_like_number function may do what you want it to do.

like image 152
Leon Timmermans Avatar answered Feb 06 '26 07:02

Leon Timmermans