Programming Fundamentals/Conditions/Perl: Difference between revisions

From Wikiversity
Jump to navigation Jump to search
Content deleted Content added
Creating
(No difference)

Revision as of 04:19, 3 February 2017

conditions.pl

#!/usr/bin/perl

# This program asks the user to select Fahrenheit or Celsius conversion
# and input a given temperature. Then the program converts the given 
# temperature and displays the result.

sub to_celsius 
{
    my $f;
    my $c;
    
    print "Enter Fahrenheit temperature:", "\n";
    $f = <>;
    chomp($f);
    $c = ($f - 32) * 5 / 9;
    print $f . "° Fahrenheit is " . $c . "° Celsius", "\n";
}

sub to_fahrenheit 
{
    my $c;
    my $f;
    
    print "Enter Celsius temperature:", "\n";
    $c = <>;
    chomp($c);
    $f = $c * 9 / 5 + 32;
    print $c . "° Celsius is " . $f . "° Fahrenheit", "\n";
}

sub main
{
    my $choice;
    
    print "Enter F to convert to Fahrenheit or C to convert to Celsius:", "\n";
    $choice = <>;
    chomp($choice);
    if ($choice eq "C" || $choice eq "c") 
    {
        to_celsius();
    }
    elsif ($choice eq "F" || $choice eq "f") 
    {
        to_fahrenheit();
    }
    else 
    {
        print "You must enter C to convert to Celsius or F to convert to Fahrenheit!", "\n";
    }
}

main()

Try It

Copy and paste the code above into one of the following free online development environments or use your own Perl compiler / interpreter / IDE.

See Also