Programming Fundamentals/Arrays/Perl
Appearance
arrays.pl
[edit | edit source]#!/usr/bin/perl
# This program uses arrays to display temperature conversion tables
# and temperature as an array subscript to find a given conversion.
#
# References:
# https://www.mathsisfun.com/temperature-conversion.html
# https://en.wikibooks.org/wiki/Perl_Programming
sub build_c
{
$size = $_[0];
my @c;
my $index;
my $value;
for ($index = 0; $index <= $size; $index += 1)
{
$value = $index * 9 / 5 + 32;
push(@c, $value);
}
return @c;
}
sub build_f
{
$size = $_[0];
my @f;
my $index;
my $value;
for ($index = 0; $index <= $size; $index += 1)
{
$value = ($index - 32) * 5 / 9;
push(@f, $value);
}
return @f;
}
sub display_array
{
my ($name, @array) = @_;
my $index;
for ($index = 0; $index <= @array - 1; $index += 1)
{
print $name . "[" . $index . "] = " . $array[$index], "\n";
}
}
sub find_temperature
{
my $c = $_[0];
my @c = @$c;
my $f = $_[1];
my @f = @$f;
my $temp;
my $size;
$size = minimum($#c, $#f);
do
{
print "Enter a temperature between 0 and ". $size . "\n";
$temp = <>;
chomp($temp);
} while $temp < 0 || $temp > $size;
print $temp . "° Celsius is " . $c[$temp] . "° Fahrenheit\n";
print $temp . "° Fahrenheit is " . $f[$temp] . "° Celsius\n";
}
sub minimum
{
my $value1 = $_[0];
my $value2 = $_[1];
my $result;
if ($value1 < $value2)
{
$result = $value1;
}
else
{
$result = $value2;
}
return $result
}
sub main()
{
my @c;
my @f;
@c = build_c(100);
@f = build_f(212);
display_array("C", @c);
display_array("F", @f);
find_temperature(\@c, \@f);
}
main();
Try It
[edit | edit source]Copy and paste the code above into one of the following free online development environments or use your own Perl compiler / interpreter / IDE.