Perl: a program to find the median

Tutoring stats, you discuss the median.  The tutor introduces a Perl program that finds it.

I defined the median back in my May 6 post. It’s preferred over the mean in some realms; I’ll explore the reason another time.

Today, we’ll look at a Perl program that finds the median. It’s a great way to jump-start the Perl-programming discussion, as well as show off a couple of Perl’s built-in functions. Here it is:


#!/usr/bin/perl

@lst=sort{$a <=> $b}@ARGV;
#uses Perl’s built-in sort to write the numbers, in ascending order, #into @lst
$n=0;
foreach(@ARGV){
$n++;
} #this loop counts the numbers given to the program
if($n%2==0){#if the list has an even number of values
$num1=$lst[$n/2-1];
#arrays start at 0, so you need to adjust down one place when #referencing.

$num2=$lst[$n/2];
$med=($num1+$num2)/2;
}
else{ #the list has an odd number of values
$med=$lst[($n-1)/2];
}
print “The list you entered is\n\n”;
foreach $one(@ARGV){
print “$one “;
}
print “\n\n”; #makes space for reading
print “The list in ascending order is\n\n”;
foreach $one(@lst){
print “$one “;
}
print “\n\n”;
print “The median is $med :)”;
print “\n\n”;

Notice the % on line 9. It’s the modulus operator, and gives the remainder of a division. If you divide by 2 and get a remainder of 0, the number must be even.

This program will serve as a platform from which to launch discussions in future posts. Stay tuned:)

Sources:

McGrath, Mike. Perl in easy steps. Warwickshire: Computer Step, 2004.

Robert’s Perl Tutorial

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply