Perl脚本中的语法错误

时间:2013-03-08 18:15:53

标签: perl

通过提问来获得减分的风险,我正在为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 ") {"...at line 33, near "}" ...等。我唯一拥有的内容,例如第27行,是")""{"之间的空格。就我所见,作者提供的解决方案几乎与我的脚本一致,除了作者使用while (not exists $rates{$from}) { ... }。 我是否误解了“ne”的用法?或者我的脚本有什么问题吗?非常感谢。

2 个答案:

答案 0 :(得分:5)

您的While大写W 开头。 Perl区分大小写,应该是while

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

答案 1 :(得分:3)

ne“不等于”。你的第一个while循环使用它,但它永远不会像你写东西那样得到错误的条件。你将永远陷入那个循环中。一个单词永远不会匹配一个数字。这就是为什么你要检查密钥是否not exists

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

而且,正如Cthulhu所说,你正在调用While而不是正确的while