Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: output difficult to understand

by Athanasius (Chancellor)
on Feb 11, 2014 at 13:04 UTC ( #1074410=note: print w/replies, xml ) Need Help??

in reply to output difficult to understand

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:

  1. It avoids repeating the same code over and over.
  2. 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,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1074410]
[marto]: good morning all

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2018-06-25 08:27 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.