您好我刚刚开始学习Perl。我有这个简单的温度应用但它没有编译,我不明白什么是错误&我该怎么办呢?
你能指出我做错了什么吗?我如何解决它们:
#!/usr/local/bin/perl
use strict;
use warnings;
use constant false >= 0;
use constant true >= 1;
# Experimentation: Array & Hashes:
my @ar = ("a", "b", "c"); # error here
print $ar, "\n";
print $ar[0], "\n";
print $#ar, "\n";
print "The size of array = $#ar \n";
print "Trying to print $ar[1] within a string: ", $ar[1], " \n";
my %ha = ( "a" => 1, "b", "c", "d" ); # error here
print $ha, "\n";
print $ha{"a"}, "\n";
print $#ha, "\n";
print "The size of hash = $#ha \n";
print "Trying to print $ha{'b'} within string: ", $ha{'b'}, " \n";
# Functions:
sub isfloat
{
my $val = shift;
return $val =~ m/^\d+.\d+$/;
}
sub toFahrenheit
{
my $val = @_[0];
# if param var is a float
if ( isFloat($val) == 0 ) # Error here: Scalar value @_[0] better written as $_[0]
{
return -1;
}
return ( ($val * (9/5)) + 32 );
}
sub toCelsius
{
if ( isFloat(@_[0]) == 0 )
{
return -1;
}
return ( (@_[0] - 32) * (5/9) );
}
# Main Program:
my $programEnd = 0;
while ( $programEnd == 0 )
{
my $menu = "*** Welcome to Temperature Converter *** \n\n1. Convert from Celsius to Fahrenheit \n2. Convert from Fahrenheit to Celsius \n3. Exit \n Enter decision (1,2 or 3): ";
print $menu;
my $decision = <>;
if ( $decision == 3 )
{
$programEnd = 1;
# Could also just do this
# break;
}
print "Please enter a number: ";
my $val = <>;
if ( isfloat($val) )
{
$conVal = -1;
if ( decision == 1 )
{
$conVal = toFahrenheit( $val );
print $val, " C in Fahrenheit is: ", $conVal, " F \n";
}
else
{
$conVal = toCelsius( $val );
print $val, " F in Celsius is: ", $conVal, " C \n";
}
}
else { print $val, " is not a number \n"; }
}
答案 0 :(得分:6)
关于“Subroutine BEGIN重新定义”的无用信息实际上是由以下两行引起的:
use constant false >= 0;
use constant true >= 1;
你的意思是:
use constant false => 0;
use constant true => 1;
错误“标量值@_ [0]更好地写为$ _ [0]”是因为在你引用数组@arr
的元素时在perl中,你说$arr[0]
,而不是@arr[0]
,因为元素本身是标量。
答案 1 :(得分:2)
>=
≠=>