How to check if a value is numeric, alphanumeric or alphanumeric in Perl?

I have an array whose values ​​are entered by the user as:

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

Now I want to check each value in the array to see if it is numeric, alphanumeric (a-zA-Z) or alphanumeric and stores them in other corresponding arrays.

I did:

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

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

It works. Similarly, I want to check the alphabet and alphanumeric values

Alphanumeric example: fr43 6t$ $eed5 *jh

+3
source share
5 answers

, , , , , . , POSIX [:alphanum:] , , 6t $$ eed5 * jh . , [:punct:] char. . Regex cheat sheet.

, , tokens.txt, :

aa df rrr5 4323 54 hjy 10 gj @fgf% d fr43 6t $$ eed5 * jh

perl script:

#!/usr/bin/perl -w
use warnings;
use diagnostics;
use strict;
use Scalar::Util qw( looks_like_number );


my $str =<>;
my @temp = split(" ",$str);

my @num = grep { looks_like_number($_) } @temp;
my @char = grep /^[[:alpha:]]+$/, @temp;
my @alphanum = grep /^[[:alnum:][:punct:]]+$/, @temp;

print "Numbers: " . join(' ', @num) . "\n";
print "Alpha: " . join(' ', @char) . "\n";
print "Alphanum: " . join(' ', @alphanum) . "\n";

:

cat tokens.txt | ./tokenize.pl

:

: 4323 54 10
: aa df hjy gj
Alphanum: aa df rrr5 4323 54 hjy 10 gj @fgf% d fr43 6t $$ eed5 * jh

, , @ %, , $ *.

, Alphanum:

my @alphanum = grep /^[[:alnum:]\$\*]+$/, @temp;

: 4323 54 10
: aa df hjy gj
: aa df rrr5 4323 54 hjy 10 gj fr43 6t $$ eed5 * jh

+3

Perl POSIX, :

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

, Scalar:: Util looks_like_number , .

+7

- .

my $input = 'aa df rrr5 4323 54 hjy 10 gj @fgf %d';
my %tests = ( 
    num   => '\d+',
    alpha => '[[:alpha:]]+', 
    alnum => '[[:alnum:]]+' 
);

my %res;
for my $t (keys %tests) {
    for (split(' ', $input)) {
        push(@{ $res{$t} }, $_) if (/^$tests{$t}$/i);
    }
}
+1

:

 /^[a-z]+$/i

-:

 /^[a-z0-9]+$/i

:

: - . fr43 6t $$ eed5 * jh

, , , , -,

 /^[[:graph:]]+$/

ASCII, .

, .

0

(//... ), Perl :

sub test_num {
    no warnings "all";
    $b = "$_[0]"; 
    $a = $b + 0; 
    return ($a eq $b);
}
push(@num, $tmp) if (test_num($tmp));

( $b = "$_[0]"; , - $tmp - test_num - )

0

Source: https://habr.com/ru/post/1740126/


All Articles