Programming Fundamentals/Functions/Perl

functions.pl edit

#!/usr/bin/perl

# This program asks the user for a Fahrenheit temperature, 
# converts the given temperature to Celsius,
# and displays the results.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Perl_Programming

sub get_fahrenheit
{
    my $fahrenheit;
    
    print "Enter Fahrenheit temperature: ";
    $fahrenheit = <>;
    chomp($fahrenheit);
    
    return $fahrenheit
}

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

sub display_result 
{
    my ($fahrenheit, $celsius) = @_;
    
    print $fahrenheit . "° Fahrenheit is " . $celsius . "° Celsius", "\n";
}

sub main
{
    my $fahrenheit;
    my $celsius;

    $fahrenheit = get_fahrenheit();
    $celsius = calculate_celsius($fahrenheit);
    display_result($fahrenheit, $celsius);
}

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