2013-03-08 67 views
0

如果问这个问题可能导致减号,我正在寻求Perl解释器拾取错误的帮助。这是Beginning Perl的一个家庭作业问题。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行,是")""{"之间的空格。就我所知,作者提供的解决方案几乎与我的脚本相同,只不过作者使用。 我误解了“ne”的用法吗?或者我的脚本有什么问题吗?非常感谢。

+0

是的,你误会了ne;我不确定你认为它做了什么? – ysth 2013-03-08 18:28:01

+1

问题并不总是得票低。不好的问题(例如,包括整个源文件而不是有问题的那些)会降低投票率。 – darch 2013-03-08 20:49:54

回答

5

您的While开头的首字母W。 Perl区分大小写,应该是while。如上所述,使用是正确的。在您的代码中,您正在比较字符串$from对应的$from中的%rates散列。无论如何这都不是真的。

+0

非常感谢!太糟糕了,我只能选择一个答案来给予“大拇指”。 – 2013-03-08 18:38:06

3

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

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

而且,正如克苏鲁所说的,你调用While而不是正确的while

+0

+1。我看到你已经覆盖了'while()':) – 2013-03-08 18:30:58