繁体   English   中英

Perl脚本中的语法错误

[英]syntax errors in a Perl script

冒着通过提问来获得减分的风险,我正在寻求帮助以解决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";

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

Your While大写字母W开头。 Perl区分大小写,应该花一段while

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

ne是“不等于”。 您的第一个while循环使用了它,但是您编写东西的方式永远不会出错。 您将始终陷于该循环中。 单词永远不会与数字匹配。 这就是为什么您要检查密钥是否not exists

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

而且,正如克苏鲁提到的那样,您调用的是While而不是适当的while

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM