Hi All,
Is there any code in Perl which can differentiate between numeric and non-numeric input?
Hi All,
Is there any code in Perl which can differentiate between numeric and non-numeric input?
The most common way:
Use regular expression.
Alternative (probably a better) way:
cbkihong@cbkihong:~$ perl -MScalar::Util -e
'print(Scalar::Util::looks_like_number("-8.90e10")?"Looks like a number.\n":"Not a number.\n")'
Looks like a number.
cbkihong@cbkihong:~$ perl -MScalar::Util -e
'print(Scalar::Util::looks_like_number("89d")?"Looks like a number.\n":"Not a number.\n")'
Not a number.
Hi ,
Below is my Perl code using regular expression. but it doesn;t seem to work.
Can anybody tell me what's wrong with my code ?
#!/usr/bin/perl
print "Enter a term: ";
$Input = <STDIN>;
print "\n";
if ($input == [0-9]) {
print "$Input is numeric\n";
}
else {
print "$Input is non-numeric\n";
}
#!/usr/bin/perl
print "Enter a term: ";
$input = <STDIN>;
print "\n";
if ($input =~ /^[0-9]+$/) {
print "$Input is numeric\n";
}
else {
print "$Input is non-numeric\n";
}
i don't intend to flame you, but wish to point out a few deficiencies in your code - it doesn't consider negative numbers, and real numbers, in current form, it is identifying natural numbers, along with zero
this one identifies integers, real numbers, and negative numbers as well:
#!/usr/bin/perl
use strict;
print "Enter a number: ";
chomp (my $num = <STDIN>);
if ($num =~ m/^-?\d+$/) {
print "An integer \n";
}
elsif ($num =~ m/^-?\d+[\/|\.]\d+$/) {
print "real number! \n";
}
else {
print "not a number \n";
}
#!/usr/bin/perl
print "Enter a term: ";
$input = <STDIN>;
print "\n";
if ( $input =~ /^[\+-]*[0-9]*\.*[0-9]*$/ && $input !~ /^[\. ]*$/ ) {
print "$Input is numeric\n";
}
else {
print "$Input is non-numeric\n";
}
if you don't want to consider --45 as numeric:
if ( $input =~ /^[\+-]?[0-9]*\.*[0-9]*$/ && $input !~ /^[\. ]*$/ ) {
and 56..34 doesn't seem to be numeric, so how about:
if ( $input =~ /^[\+-]?[0-9]*\.?[0-9]*$/ && $input !~ /^[\. ]*$/ ) {
Hi Anbu,
I tried your code but it's not working.
$ cat xxx.pl
#!/usr/bin/perl
print "Enter a term: ";
$Input = <STDIN>;
if ($input =~ /[3]*[0-9]*\.*[0-9]$/ && $input !~ /[4]$/) {
print "$Input is numeric\n";
}
else {
print "$Input is non-numeric\n";
}
$ perl xxx.pl
Enter a term: 10
10
is non-numeric
$ perl xxx.pl
Enter a term: 23
23
is non-numeric
$Input = <STDIN>;
if ($input =~ /^[\+-]*[0-9]*\.*[0-9]*$/ && $input !~ /^[\. ]*$/) {
Variable names are case sensitive and also incorporate the Yogesh Sawants comments.
$input = <STDIN>;
if ( $input =~ /^[\+-]?[0-9]*\.?[0-9]*$/ && $input !~ /^[\. ]*$/ ) {
Hi Anbu,
Thanks for the guidance. it works fine now!
How to invoke the above perl code in ksh script.
Thanks in adv.
Br//
Vijay