我正在尝试运行这个 Perl 程序。
#!/usr/bin/perl
# --------------- exchange.pl -----------------
&read_exchange_rate; # read exchange rate into memory
# now let's cycle, asking the user for input...
print "Please enter the amount, appending the first letter of the name of\n";
print "the currency that you're using (franc, yen, deutschmark, pound) -\n";
print "the default value is US dollars.\n\n";
print "Amount: ";
while (<STDIN>) {
($amnt,$curr) = &breakdown(chop($_));
$baseval = $amnt * (1/$rateof{$curr});
printf("%2.2f USD, ", $baseval * $rateof{'U'});
printf("%2.2f Franc, ", $baseval * $rateof{'F'});
printf("%2.2f DM, ", $baseval * $rateof{'D'});
printf("%2.2f Yen, and ", $baseval * $rateof{'Y'});
printf("%2.2f Pound\n\nAmount: ", $baseval * $rateof{'P'});
}
sub breakdown {
@line = split(" ", $_);
$amnt = $line[0];
if ($#line == 1) {
$curr = $line[1];
$curr =~ tr/a-z/A-Z/; # uppercase
$curr = substr($curr, 0, 1); # first char only
} else { $curr = "U"; }
return ($amnt, $curr);
}
sub read_exchange_rate {
open(EXCHRATES, "
每当它到达第 17 行 ( $baseval = $amnt * (1/$rateof{$curr})
) 时,我都会收到错误消息Illegal division by zero
。
怎么了?
我是 Perl 的新手,所以请解释一下你的答案。
这只发生在 Strawberry Perl 中。ActivePerl 可以工作,但它会将所有货币转换列为 0.0。
更新:我将代码更改为如下所示:
#!/usr/bin/perl
&read_exchange_rate; # read exchange rate into memory
# now let's cycle, asking the user for input...
print "Please enter the amount, appending the first letter of the name of\n";
print "the currency that you're using (franc, yen, deutschmark, pound) -\n";
print "the default value is US dollars.\n\n";
print "Amount: ";
while (<STDIN>) {
($amnt,$curr) = &breakdown(chomp($_));
$baseval = eval { $amnt * (1/$rateof{$curr}) };
printf("%2.2f USD, ", $baseval * $rateof{'U'});
printf("%2.2f Franc, ", $baseval * $rateof{'F'});
printf("%2.2f DM, ", $baseval * $rateof{'D'});
printf("%2.2f Yen, and ", $baseval * $rateof{'Y'});
printf("%2.2f Pound\n\nAmount: ", $baseval * $rateof{'P'});
}
sub breakdown {
@line = split(" ", $_);
$amnt = $line[0];
if ($#line == 1) {
$curr = $line[1];
$curr =~ tr/a-z/A-Z/; # uppercase
$curr = substr($curr, 0, 1); # first char only
} else { $curr = "U"; }
return ($amnt, $curr);
}
sub read_exchange_rate {
open EXCHRATES, "<exchange.db" or die "$!\n";
while ( <EXCHRATES> ) {
chomp; split;
$curr = $_[0];
$val = $_[1];
$rateof{$curr} = $val;
}
close(EXCHRATES);
}
现在,当我使用 Open With(是的,我在 Windows 上)时,我在 Strawberry Perl 中得到了这个:
No such file or directory
但如果我双击它,它开始正常,但会话看起来像这样:
Please enter the amount, appending the first letter of the name of
the currency that you're using (franc, yen, deutschmark, pound) -
the default value is US dollars.
Amount: 5 y
0.00 USD, 0.00 Franc, 0.00 DM, 0.00 Yen, and 0.00 Pound
Amount:
显然有些不对劲。chop
我已经更改了to的所有实例chomp
。现在我该怎么做?