Daniel Moree wrote:
WipeOut wrote:
I am having a problem in a perl script that I can't seem to find an
answer for..
The $cost and $retail vars come from another part of the script and
would be something like 000134.345 and 000220.202 respectively..
I an then trying to use these values in a calculation like this..
$profit = ($retail - $cost) / $retail * 100;
But I get the following error..
./avgprofit.pl PriceList.txt
Illegal division by zero at ./avgprofit.pl line 35, <> line 1.
If is substitute the values directly into the calculation it works
perfectly..
Anyone got any ideas?
Thanks..
I'd help, but i'd need to see the rest of the file.
What the problem mostlikely is, is that the variable $retail and $cost
were initialized inside a sub or such. Try putting at the very top of
your perl file something like this.
my $retail = 0;
my $cost = 0;
if you need to change some stuff do so. But it seems like it's not
reading it as a global but a local variable.
Daniel
Hi Daniel..
Its a very simple script for taking a fixed length database file and
creating a CSV created from my limited perl ability.. :)
Thanks for your help..
Here is the whole script (may be some line wrapping)..
#!/usr/bin/perl
#Set up first line field desc.
#print "\"PRODUCTCODE\";\"PRODUCT\";\"COST_PRICE\";\"PRIC E\";\"PROFIT\";\n";
# Read from standard input or file specified on command line.
while (<>) {
# Specify each field as a or A with its width.
# Use a to preserve trailing spaces, A to strip them.
@fields = unpack('A18 A30 A1 A9 A9 A3 A2 A18 A2 A11 A2 A9 A3 A9 A3 A9
A3 A1 A4 A7 A1 A1', $_);
# Insert decimal point into price fields.
$fields[3] =~ s/(...)$/.$1/;
$fields[4] =~ s/(...)$/.$1/;
# Clean up and substitutions.
foreach $f (@fields) {
# Replace \'s with /'s
$f =~ s/(\\)/\//g;
# Remove leading spaces
$f =~ s/^\s//;
# Double any " characters, and then enclose in "
$f =~ s/"/""/g;
}
# Profit calculation.
$cost = $fields[3];
$retail = $fields[4];
$profit = ($retail - $cost) / $retail * 100;
#$profit = (220.202 - 000134.567) / 220.202 * 100;
# Print out seperated list except where price field is less than
000005.000 (zero).
if ($fields[4] gt "000005.000") {
# "PRODUCTCODE";"PRODUCT";"COST_PRICE";"PRICE;"PROFI T"
print "$fields[0];$fields[1];$cost;$retail;$profit;\n";
}
}
#end