Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, I have a very silly/stupid question, Is there a possiblity to print a line for example "Too many fails for student $s1\n"

The input file is similar to this
XY,50,weret,30,reewrw XY,25,weret,30,rerwe yz,45,ferr,55,rwree YZ,90,ferr,55,deert
I need to check whether the avg(4th column) is greater then 50 if not should print "too many fails"; But the problem is , since I loop through the class(first coumns)(for loop ) and then through the students details(hash key->column 5)) (foreach loop), so I get them printed more than once depending on the number of students available per class.

Is there any way to restrict to print the statement once irrespective of the number of students? Or could we avoid the printing if the class (first column) is already reported? Thanks inadvance

Replies are listed 'Best First'.
Re: print statement to avoid printing aline more than once
by moritz (Cardinal) on May 10, 2011 at 21:03 UTC

    Please show the code you are using now, so that we can suggest how to change it.

    In general one can weed out duplicates by tracking printed items in a hash, but maybe that isn't necessary - hard to tell without seeing actual code, more input examples and desired output.

Re: print statement to avoid printing aline more than once
by thewebsi (Scribe) on May 10, 2011 at 21:28 UTC

    Usually I do something like this:

    print "Too many fails for student $s1\n" if ! $students{$s1}++ and $avg < 50;

Re: print statement to avoid printing aline more than once
by wind (Priest) on May 10, 2011 at 21:49 UTC

    Just put your scores into an array and calculate the average using List::Util sum in a second loop.

    use List::Util qw(sum); use strict; use warnings; my %scores; while (<DATA>) { chomp; my @fields = split ','; push @{$scores{$fields[2]}}, $fields[3]; } for my $student (keys %scores) { my $average = sum(@{$scores{$student}}) / @{$scores{$student}}; print "you bad boy, $student, $average\n" if $average < 50; } __DATA__ XY,50,weret,30,reewrw XY,25,weret,30,rerwe yz,45,ferr,55,rwree YZ,90,ferr,55,deert