2015-10-21

[Perl]文字檔案抓取

先建立一個檔案,檔名grades.txt Noel 25 Ben 76 Clementine 49 Norm 66 Chris 92 Doug 42 Carol 25 Ben 12 Clementine 0 程式碼
#!/usr/local/bin/perl
=head REM
   抓取檔案計算成績
=end REM
=cut

open (GRADES , "grades.txt") or die "can't not open grades: $!\n";
while($line =<GRADES>){
	($student,$grade) = split(" ", $line);
	$grades{$student}.= $grade." ";
}

foreach $student (sort keys %grades){
	$scores = 0;
	$total = 0;
	@grades = split(" ",$grades{$student});    #建立@grades Array
	foreach $grade (@grades){
		$total += $grade;
		$scores ++;
	}
	$average = $total / $scores;
	print "$student: $grades{$student}\tAverage: $average\n";
}
  結果呈現



沒有留言:

張貼留言