beginer_in_perl has asked for the wisdom of the Perl Monks concerning the following question:

Is an option of judging the alpha or numeric chartacter available in perl. Just as in 'c' we have 'isdigit' or 'isalpha' help is eagerly awaited.

Replies are listed 'Best First'.
Re: character test functions
by davido (Cardinal) on Nov 03, 2005 at 07:50 UTC

    We have regular expressions, and they have metacharacters and character classes.

    if ( $char =~ /\d/ ) { print "It's a digit.\n"; } if ( $char =~ /\w/ ) { print "It's a word-like character.\n"; } if ( $char =~ /[a-zA-Z]/ ) { print "It's an asciibetical alpha character.\n"; } if ( $char =~ /[[:alpha:]]/ ) { print "It's an alpha character.\n"; }

    ...just to name a few possibilities. See perlre for details.


    Dave

      Agreed, just let me add that you have to use locale; if you want these character classes to be locale-aware. This is like setlocale(LC_ALL, ""); in C, but it's only effective in the lexical scope of the declaration.

      Update: the POSIX module has an isdigit function, but you have to apply it to a string, not a character code.

Re: character test functions
by xdg (Monsignor) on Nov 03, 2005 at 10:23 UTC

    There's also CPAN. A quick search on "alphanumeric" revealed Data::Validate. More extensive digging revealed Scalar::Util::Numeric and Ctype (literally, the ctype.h tests).

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Re: character test functions
by ioannis (Abbot) on Nov 03, 2005 at 07:54 UTC
    Here is one way, for non-Unicode strings:
    my $alpha = 'J'; my $num = '3'; $alpha =~ /^ [[:alpha:]] $/x and print 'correct'; $alpha !~ /^ [[:digit:]] $/x and print 'correct'; $num =~ /^ [[:digit:]] $/x and print 'correct'; $num !~ /^ [[:alpha:]] $/x and print 'correct';