开发者

Simple compiler Errors: Too new to Perl to know how to fix them

Hello I just began learning Perl. I have this simple temperature application but it is not compiling, I dont understand what are the errors & how I can fix them?

Can you point out what I am doing wrong & how I fix them:

#!/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
pri开发者_C百科nt $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"; }


}


The unhelpful messages about "Subroutine BEGIN redefined" actually is caused by these two lines:

use constant false >= 0;
use constant true  >= 1;

You mean them to be:

use constant false => 0;
use constant true  => 1;

The error "Scalar value @_[0] better written as $_[0]" is because in perl when you refer to an element of an array @arr, you say $arr[0], not @arr[0], because the element itself is a scalar.


>==>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜