Programming Fundamentals/Conditions/Perl

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 get_temperature
{
    my ($label) = @_;
    
    my $temperature;
    
    print "Enter " . $label . " 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_label, $result, $to_label) = @_;
    
    print $temperature . "° " . $from_label . " is " . $result . "° " . $to_label, "\n";
}

sub main
{
    my $choice;
    my $temperature;
    my $result;
    
    $choice = get_choice();
    if ($choice eq "C" || $choice eq "c") 
    {
        $temperature = get_temperature("Fahrenheit");
        $result = calculate_celsius($temperature);
        display_result($temperature, "Fahrenheit", $result, "Celsius")
    }
    elsif ($choice eq "F" || $choice eq "f") 
    {
        $temperature = get_temperature("Celsius");
        $result = calculate_fahrenheit($temperature);
        display_result($temperature, "Celsius", $result, "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