0

冒着通过提问得到减分的风险,我正在为 Perl 解释器发现的错误寻求帮助。这是来自Beginning Perl 的一个家庭作业问题。

问:修改货币程序以不断询问货币名称,直到输入有效的货币名称。

#! /usr/bin/perl
#convert.pl
use warnings;
use strict;

my ($value, $from, $to, $rate, %rates);
%rates = (
    pounds => 1,
    dollars => 1.6,
    marks => 3,
    "french frances" => 10,
    yen => 174.8,
    "swiss frances" => 2.43,
    drachma => 492.3,
    euro => 1.5
);

print "currency exchange formula -
pounds, dollars, marks, french frances, 
yen, swiss frances, drachma, euro\n";


print "Enter your starting currency: ";
$from = <>;
chomp($from);

While ($from ne $rates{$from}) {

    print "I don't know anything about $from as a currency\n";
    print "Please re-enter your starting currency:";
    $from = <>;
    chomp($from);
    }

print "Enter your target currency: ";
$to =<>;
chomp($to) ;

While ($to ne $rates{$to}) {

    print "I don't know anything about $to as a currency\n";
    print "Please re-enter your target currency:";
    $to = <>;
    chomp($to);
    }


print "Enter your amount: ";
$value = <>;
chomp ($value);
    if ($value == 0) {
    print "Please enter a non-zero value";
    $value = <>;
    chomp ($value);
    }

$rate = $rates{$to} / $rates{$from};
print "$value $from is ", $value*$rate, " $to.\n";

识别出 4 个错误,都在while循环内,例如"syntax error at line 27, near ") {"or ...at line 33, near "}"... 等。我唯一的东西,例如第 27 行,是 and 之间的")"空格"{"。据我所知,作者提供的解决方案与我的脚本几乎相同,除了作者使用while (not exists $rates{$from}) { ... }. 我误解了“ne”的用法吗?或者我的脚本还有什么问题吗?非常感谢。

4

2 回答 2

5

While大写字母 W开头。Perl 区分大小写,应该是while.

如您所述使用while (not exists $rates{$from}) { ... }是正确的。在您的代码中,您将字符串与哈希中对应$from数字进行比较。无论如何,这不会是真的。 $from%rates

于 2013-03-08T18:21:22.640 回答
3

ne是“不等于”。你的第一个while循环使用它,但它永远不会用你写东西的方式得到一个错误的条件。你将永远被困在那个循环中。一个词永远不会匹配一个数字。这就是为什么您要检查密钥是否存在的原因not exists

正确的做法是打印出您知道的货币,例如say for keys %rates并使用do {...} while (...)循环。

而且,正如 Cthulhu 所提到的,您正在调用While而不是正确的while.

于 2013-03-08T18:24:17.313 回答