2012-10-19 75 views
1

我在Perl中有这样的问题: 要编写一个Perl脚本,它会询问用户温度,然后询问是否将其转换为度数Celius或华氏度。执行转换并显示答案。对于温度转换的公式为:Perl华氏转换为摄氏温度,反之亦然

1) Celsius to Fahrenheit:C=(F-32) x 5/9 
2) Fahrenheit to Celsius:F=9C/5 + 32 

我的脚本是:

#!/usr/bin/perl 
use strict; 
use warnings; 

print "Enter the temperature: "; 
my $temp = <STDIN>; 
print "Enter the Conversion to be performed:"; 
my $conv = <STDIN>; 
my $cel; 
my $fah; 

if ($conv eq 'F-C') { 

    $cel = ($temp - 32) * 5/9; 
    print "Temperature from $fah degree Fahrenheit is $cel degree Celsius"; 
} 

if ($conv eq 'C-F') { 

    $fah = (9 * $temp/5) + 32; 
    print "Temperature from $cel degree Celsius is $fah degree Fahrenheit"; 
} 

我从键盘输入$ TEMP和$ CONV后,空白输出将appear.Where我该怎么错了?请帮忙。提前致谢。

+3

如果其他人正在寻找它:有一个CPAN模块可以做到这一点:[Convert :: Temperature](https://metacpan.org/module/Convert::Temperature) – simbabque

回答

2

输入后,你的变量中会有一个换行符。使用chomp摆脱它。

然后会有第二个问题 - 您在输出语句中使用$fah$cel。这应该是$temp变量,否则你会得到这样的错误:(。)

在串联或字符串中使用未初始化值$ CEL的...

这里是更新的代码:

#!/usr/bin/perl 
use strict; 
use warnings; 
print "Enter the temperature: "; 
my $temp = <STDIN>; 
chomp($temp); 
print "Enter the Conversion to be performed:"; 
my $conv = <STDIN>; 
chomp($conv); 
my $cel; 
my $fah; 
if ($conv eq 'F-C') 
{ 
$cel = ($temp - 32) * 5/9; 
print "Temperature from $temp degree Fahrenheit is $cel degree Celsius"; 
} 
if ($conv eq 'C-F') 
{ 
$fah = (9 * $temp/5) + 32; 
print "Temperature from $temp degree Celsius is $fah degree Fahrenheit"; 
} 
+0

非常感谢。 – user1613245

2

您不会考虑将在用户输入中的新行字符。

在您将<STDIN>指定给它之后,在每个标量上调用chomp

+0

是的。谢谢。在我为$ temp和$ conv调用chomp之后,我得到了所需的输出。 – user1613245

0

你也可以尝试Convert::Pluggable像这样:

use Convert::Pluggable; 

my $c = new Convert::Pluggable; 

my $result = $c->convert({ 'factor' => 'someNumber', 'from_unit' => 'C', 'to_unit' => 'F', 'precision' => 'somePrecision', });