http://qs321.pair.com?node_id=680449


in reply to Students Rank calculation for the below perl script

There are a few things I would do differently

Anyway this is my version, it still fails to report marks for Ms. O'Hara but at least you will get a warning, and I have to leave something for you;-) The other change is to not explicitly code the number of tests, this will work if the input file has results of four tests.

#!/net/perl/5.10.0/bin/perl use strict; use warnings; use List::Util qw(sum); my $input_file = 'marks.txt'; open my $DATA, '<', $input_file or die "Can't open $input_file: $!\n"; while ( my $line = <$DATA> ) { next if $line =~ /^NAME/; chomp $line; if ( $line =~ /^\w+,\w+(?:,\d+)+$/ ) { my ( $first_name, $last_name, @marks ) = split ',', $line; my $totalmarks = sum @marks; my $average = sprintf "%.2f", $totalmarks / @marks; my $fail = 0; foreach my $mark (@marks) { $fail ||= checkfail($mark); } if ( !$fail ) { print "$first_name $last_name\t@marks \t$totalmarks\t$aver +age\n"; } else { print "$first_name $last_name\t@marks \t\n"; } } else { warn "Invalid input: $line\n"; } } close $DATA or die "Can't close $input_file: $!\n"; #To check whether the student failed sub checkfail { my $marks = shift; return $marks < 35; } john michael 100 50 60 210 70.00 sam shane 50 60 70 180 60.00 tom christo 30 40 50

You may wish to give consideration to using Text::CSV_XS for parsing comma delimited text files.

Update: two small code modifications kindly suggested by moritz.

Replies are listed 'Best First'.
Re^2: Students Rank calculation for the below perl script
by moritz (Cardinal) on Apr 15, 2008 at 08:14 UTC
    Just two minor remarks:
    my $totalmarks = reduce { $a + $b } @marks;

    If you resort to List::Util (Which isn't a bad idea at all) you can just as well use sum @marks.

    my $fullname   = "";

    Since you don't use it, you don't have to declare it.