Click to See Complete Forum and Search --> : Perl - Finding the Smallest Number


bananasplitkids
October 4th, 2010, 06:51 PM
I am learning Perl and I am currently doing a program where it should read a list of numbers, sort and print the numbers, find the sum, largest, smallest and average number. It should also compute the standard deviation.

Currently my program works but when I add the last line to find the smallest number I get the following error:
syntax error at math.pl line 58, near "print"
Execution of math.pl aborted due to compilation errors.

Can I not use that syntax to print the first number in the sorted array.


#!/usr/bin/perl


# get array size
print ("How many items?\n");
$size = <STDIN> ;
chomp ($size);

# get array values
for ($x=0; $x<$size; $x++)
{
print ("Enter number\n");
$val = <STDIN> ;
chomp ($val);
$data[$x] = $val;
}

# print array values
print ("Here is what you entered: \n");
for ($x=0; $x<$size; $x++)
{
print ("$data[$x]\n");
}

#Finding the Sum
my $total = 0;
($total+=$_) for @data;
print "The sum is $total\n";

#Finding the Average
$average=$total/$size;
print "The average is $average\n";

#Finding the Standard Deviation
#find the mean of the squares of the differences between each number and the average
my $total2 = 0;
foreach my $x (@data) {
$total2 += ($x-$average)**2;
}
my $mean2 = $total2 / $size;

#Take the square root to find standard deviation
my $std_dev = sqrt($mean2);
print $std_dev;

#Sorting the array of numbers
@sorted = sort{$a <=> $b} @data;
print "Sorted numbers:\n";
for ($x=0; $x<$size; $x++)
{
print ("$sorted[$x]\n");
}

#Printing the Largest Number
print "The largest number is $sorted[$size-1]\n"

#Printing the Smallest Number
print "The largest number is $sorted[0]\n"

ultddave
October 6th, 2010, 11:56 AM
You forgot the ";" behind the last and second last print. ;)


#Printing the Largest Number
print "The largest number is $sorted[$size-1]\n";

#Printing the Smallest Number
print "The largest number is $sorted[0]\n";


Greetz,
Dave