1

我在 Perl 中有一个问题:编写一个 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 后,会出现空白输出。我哪里出错了?请帮忙。提前致谢。

4

3 回答 3

2

您没有考虑用户输入中的换行符。

chomp在你给它赋值之后调用每个标量<STDIN>

于 2012-10-19T08:20:27.807 回答
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"; 
}
于 2012-10-19T08:22:25.793 回答
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', } );
于 2014-05-25T15:50:27.837 回答