Programming Fundamentals/Conditions/Perl

From Wikiversity
Jump to navigation Jump to search

conditions.pl[edit]

#!/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.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Perl_Programming

sub get_choice
{
    my $choice;
    
    print "Enter F to convert to Fahrenheit or C to convert to Celsius:", "\n";
    $choice = <>;
    chomp($choice);
    return $choice
}

sub process_celsius 
{
    my $temperature;
    my $result;
    
    $temperature = get_temperature("Fahrenheit");
    $result = calculate_celsius($temperature);
    display_result($temperature, "Fahrenheit", $result, "Celsius")
}

sub process_fahrenheit 
{
    my $temperature;
    my $result;
    
    $temperature = get_temperature("Celsius");
    $result = calculate_fahrenheit($temperature);
    display_result($temperature, "Celsius", $result, "Fahrenheit")
}

sub get_temperature
{
    my ($scale) = @_;
    
    my $temperature;
    
    print "Enter " . $scale . " temperature: ";
    $temperature = <>;
    chomp($temperature);
    
    return $temperature
}

sub calculate_celsius
{
    my ($fahrenheit) = @_;
    
    my $celsius;
    
    $celsius = ($fahrenheit - 32) * 5 / 9;
    
    return $celsius
}

sub calculate_fahrenheit
{
    my ($celsius) = @_;
    
    my $fahrenheit;
    
    $fahrenheit = $celsius * 9 / 5 + 32;
    
    return $fahrenheit
}

sub display_result 
{
    my ($temperature, $from, $result, $to) = @_;
    
    print $temperature . "° " . $from . " is " . $result . "° " . $to, "\n";
}

sub main
{
    my $choice;
    
    $choice = get_choice();
    if ($choice eq "C" || $choice eq "c") 
    {
        process_celsius();
    }
    elsif ($choice eq "F" || $choice eq "f") 
    {
        process_fahrenheit();
    }
    else 
    {
        print "You must enter C to convert to Celsius or F to convert to Fahrenheit!", "\n";
    }
}

main()

Try It[edit]

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[edit]