### 如何判断变量在Perl中是否具有数值？

``````if (is_number(\$x))
{ ... }
``````

## 实施例

``````#!/usr/bin/perl

use warnings;
use strict;

use Scalar::Util qw(looks_like_number);

my @exprs = qw(1 5.25 0.001 1.3e8 foo bar 1dd inf infinity);

foreach my \$expr (@exprs) {
print "\$expr is", looks_like_number(\$expr) ? '' : ' not', " a number\n";
}
``````

``````1 is a number
5.25 is a number
0.001 is a number
1.3e8 is a number
foo is not a number
bar is not a number
1dd is not a number
inf is a number
infinity is a number
``````

## 另见：

``````use Regexp::Common;
if (\$var =~ /\$RE{num}{real}/) { print q{a number}; }
``````

``````if ( length( do { no warnings "numeric"; \$x & "" } ) ) {
print "\$x is numeric\n";
}
``````

``````if (\$x  eq  \$x+0) { .... }
``````

``````sub is_integer {
defined \$_[0] && \$_[0] =~ /^[+-]?\d+\$/;
}

sub is_float {
defined \$_[0] && \$_[0] =~ /^[+-]?\d+(\.\d+)?\$/;
}
``````

``````sub isnumber
{
shift =~ /^-?\d+\.?\d*\$/;
}
``````

rexep不完美......这是：

``````use Try::Tiny;

sub is_numeric {
my (\$x) = @_;
my \$numeric = 1;
try {
use warnings FATAL => qw/numeric/;
0 + \$x;
}
catch {
\$numeric = 0;
};
return \$numeric;
}
``````

Regexp::Common中可以找到更强大的正则表达式。

``````sub is_number{
my \$n = shift;
my \$ret = 1;
\$SIG{"__WARN__"} = sub {\$ret = 0};
eval { my \$x = \$n + 1 };
return \$ret
}
``````

``````{
no warnings "numeric"; # Ignore "isn't numeric" warning
...                    # Use a variable that might not be numeric
}
``````

``````If ((\$x !~ /\D/) && (\$x ne "")) { ... }
``````

``````if ( \$value + 0 eq \$value) {
# A number
push @args, \$value;
} else {
# A string
push @args, "'\$value'";
}
``````

``````do {
no warnings "numeric";
if (\$x + 0 ne \$x) { return "not numeric"; } else { return "numeric"; }
}
``````

if（定义\$ x＆amp;＆amp; \$ x！~m / \ D /）{} 要么 \$ x = 0如果！ \$ X; if（\$ x！~m / \ D /）{}

``````    sub IS_Integer()
{
my \$Text = shift;
my \$Integer = 0;

if (\$Text =~ /\D/)
{
\$Integer = 1;
}
if (\$Text =~ /^\d+\$/)
{
\$Integer = 1;
}
if (\$Text =~ /^-?\d+\$/)
{
\$Integer = 1;
}
if (\$Text =~ /^[+-]?\d+\$/)
{
\$Integer = 1;
}
if (\$Text =~ /^-?\d+\.?\d*\$/)
{
\$Integer = 1;
}
if (\$Text =~ /^-?(?:\d+(?:\.\d*)?&\.\d+)\$/)
{
\$Integer = 1;
}
if (\$Text =~ /^([+-]?)(?=\d&\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?\$/)
{
\$Integer = 1;
}

return \$Integer;
}
``````