[作業­2] 由檔案讀取成績並計算平均 - Perl

三月 14th, 2006

功能說明:

讀取成績檔內容並計算平均,最後寫入新檔。
成績資料檔:testdata.txt (檔名改為 testdata)

實作:


#!/usr/bin/perl
use strict; 

open FILE, "testdata" or die "Can not open file: $!"; 

my @lines;
foreach (<FILE>) {
    chomp;
    split(/__/);
    my @grades = split(/,/, $_[1]);
    my $total = 0;
    my $average = 0;
    foreach my $grade (@grades) {
        $total += $grade;
    }
    $average = $total/@grades;
    my $line = $_[0].'__'.$_[1].'=>'.$average."\n";
    push @lines, $line;
} 

open OUT_FILE, ">testdata2" or die "Can not open file: $!";
print OUT_FILE @lines; 

close FILE;
close OUT_FILE;

筆記:
chop 和 chomp 的差異。
這兩個都可以刪除尾端的換行字元,但使用 chomp 是比較安全的,因為 chop 會把尾端是 0 的一併刪除,造成錯誤結果。

Other, 程式筆記

  1. No comments yet.
  1. No trackbacks yet.