in reply to Create Hash from array structure
#!/usr/local/bin/perl -w use strict; use Fcntl ':flock'; my $file = "inputdata.txt"; open(INFILE, $file) or die "File Not Found: $!"; flock(INFILE, LOCK_EX); my @students; while (<INFILE>) { push @students, [split / /, $_]; } my %hash; # where's $grades coming from? # $hash{$grades}= $students[0]*0.2 + $student[1]*0.25+$students[2]*0.2 +5 + $student +s[3]*0.3; # flock(INFILE, LOCK_UN); # don't use unlock, it's done automagically +by close() close(INFILE);
update: oops, i forgot 'my @students'
update2: ok, after you updated your code and added input and output, here's my suggestion:
use strict; use Fcntl ':flock'; my $file = "inputdata.txt"; open(FH, $file) or die "File Not Found: $!"; flock(FH, LOCK_EX); my @students; my %hash; my @mul = (0.2,0.25,0.25,0.3); while (<FH>) { my ($student, @grades) = (split ' ', $_); # split at one or more whi +tespaces my $grade = 0; for (0..$#mul) { $grade += $mul[$_] * $grades[$_] } $hash{$student} = $grade; # save the sum as a value to the student n +ame } foreach my $key(sort {$hash{$b} <=> $hash{$a}} keys %hash){ print "$key: $hash{$key}\n"; } close(INFILE);
|
|---|