Hello sonia, and welcome to the Monastery!
As parv says, the strange output occurs because the newline characters are unquoted. Here is some valuable advice I hope you will take to heart: Give yourself a safety net by starting each script with:
use strict;
use warnings;
For your script in its present form, this will result in 18 errors. The first 14 of these are easily fixed by declaring each variable with my the first time it appears:
...
my $math=<STDIN>;
...
my $sci=<STDIN>;
...
The last 4 errors are of the form:
Bareword "n" not allowed while "strict subs" in use at ...
which draws attention to the fact that the newline character \n is not quoted — hence, it’s a “bareword.”
In the hope that you may find it helpful, here is how I would approach this task:
use strict;
use warnings;
my @subjects = qw( maths science history geography );
my $sum = 0;
foreach my $subject (@subjects)
{
print "Enter percentage mark in $subject:\n";
$sum += <STDIN>;
}
printf "Your average is: %.2f%%\n", ($sum / scalar(@subjects));
The main advantages of this approach are:
- It avoids repeating the same code over and over.
- If a new subject is added, only one line (the one beginning my @subjects = ...) needs to be changed; the rest of the script will still work correctly.
Hope that helps,
|