I realise, this has been queried before but I can't seem to find a simple elegant Perl example.
I need to know if a string is a number or not. With trial and error, I have come up with the below that works.
This is anything but elegant and has been separated into multiple if / elsif for testing.
I would like to combine the string comparisons into as few as possible but seem to break the code every time I try.
print IsNumber("0777 891 777") . "\n"; # 0
print IsNumber("1.5671") . "\n"; # 1
print IsNumber("121A3D") . "\n"; # 0
print IsNumber("777") . "\n"; # 1
print IsNumber("0") . "\n"; # 1
print IsNumber("-4.567") . "\n"; # 1
print IsNumber("+9.8.97") . "\n"; # 0
print IsNumber("+9.897") . "\n"; # 1
print IsNumber("+9.8¬97") . "\n"; # 0
print IsNumber("9.8[97") . "\n"; # 0
sub IsNumber
{
my ($string) = @_;
my $valid = 0;
my $count = $string =~ tr/\.//;
if ( $string =~ m/[a-zA-Z\ \[\]]/ )
{
$valid = 0;
}
elsif ( $string =~ /[^\x00-\x7F]/ )
{
$valid = 0;
}
elsif ( $count > 1 )
{
$valid = 0;
}
elsif ( $string =~ m/[#@':;><,.{}[]=!"£$%^&*()]/ )
{
$valid = 0;
}
elsif ( $string =~ m/^[+-]?\d+$/ )
{
$valid = 1;
}
elsif ( $string =~ m/^[+-]?[0-9]+[.]?[0-9]+/ )
{
$valid = 1;
}
return $valid;
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|