zzhang2006
asked on
Perl divide by zero problem with varibles extracted from text
I have the following code, with give a dividing by zero problem. Obviously, the $fields[1] is not supposed to be zero. It print out a decimal number when direct print out. And it can be added to another varible with + and arithmetic is fine. But when it is in the denominator it it cuase such a message:
Illegal division by zero at E:\CruzerLock2\Stocks\quot e2.pl line 151, <GEN0> lin
e 13.
The code segment look like this:
my $change = sprintf "%.2f", ( $fields[4]) / ($fields[1])*100;
Is there something hidden in the fields[1] that couse this? Thanks
Illegal division by zero at E:\CruzerLock2\Stocks\quot
e 13.
The code segment look like this:
my $change = sprintf "%.2f", ( $fields[4]) / ($fields[1])*100;
Is there something hidden in the fields[1] that couse this? Thanks
ASKER
You may be right, I change it to
print "See this-> $. $fields[1] \n";
my $change = sprintf "%.2f",
( $fields[4]) /$fields[1]*100;
Then it printed:
See this-> 13
Illegal division by zero at E:\CruzerLock2\Stocks\quot e2.pl line 152, <GEN0> lin
e 13.
Does a blank means zero? Where is the "13" come from? How can I put a condition to check $fields[1] not zero or simply being a number? Thanks
print "See this-> $. $fields[1] \n";
my $change = sprintf "%.2f",
( $fields[4]) /$fields[1]*100;
Then it printed:
See this-> 13
Illegal division by zero at E:\CruzerLock2\Stocks\quot
e 13.
Does a blank means zero? Where is the "13" come from? How can I put a condition to check $fields[1] not zero or simply being a number? Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
perldoc-q "How do I determine whether a scalar is a number/whole/integer/float "
ASKER
Great! I solved my problem. Thanks
ASKER
Great!
Add a
print "$. $fields[1]\n";
before line 151 and post the output.