2011年7月24日日曜日

開発環境

  • Mac OS X Snow Leopard (OS)
  • TextWrangler(Text Editor) (いずれはBBEditを入手したい!)
  • Script言語:Perl

『続・初めてのPerl 改訂版』(Randal L. Schwartz, brian d foy, Tom Phoenix 著、伊藤 直也、田中 慎司、吉川 英興 監訳、株式会社ロングテール/長尾 高弘 訳、オライリー・ジャパン、2006年、ISBN4-87311-305-9) の6章(複雑なデータ構造の操作), 6.8(練習問題)、1を解いてみる。

 

1.

やり方の1つ。(「やり方は何通りもある」(TIMTOWTDI(There Is More Than One Way To Do It.)))

コード(TextWrangler)

#!/usr/bin/perl
use strict;
use warnings;
use Storable;

my %total_bytes;
my $total_source="total_source";

# 1つ目の追加箇所
my $total_log="total_log.dat";
if(-e $total_log){
  my $data=retrieve "total_log.dat";
  %total_bytes=%$data;
  }
# ここまで1つ目の追加箇所

while (<>){
  next if /^#/;
  my ($source, $destination, $bytes) = split;
  $total_bytes{$source}{$destination} 
    += $bytes;
  $total_bytes{$source}{$total_source} 
    += $bytes;
}
# 2つ目の追加箇所
store \%total_bytes, $total_log;
# ここまで2つ目の追加箇所

my @sources
     =sort{$total_bytes{$b}{$total_source}
     <=> $total_bytes{$a}{$total_source}}
     keys %total_bytes;
for my $source (@sources) {
  print "$source: total ",
    "$total_bytes{$source}{$total_source}",
    " bytes\n";
  my @destinations
       =sort{$total_bytes{$source}{$b} 
       <=> $total_bytes{$source}{$a}}
       keys %{$total_bytes{$source}};
  for my $destination (@destinations){
    next if $destination eq $total_source;
    print "    => $destination:",
      " $total_bytes{$source}{$destination}",
      " bytes\n";
  }
}

入出力結果(Terminal)

新しい合計(ファイル、coconet_1.datはファイル、coconet.datの最後の行にmkamimura.com sitekamimura.blogspot.com 1000を加えたもの)

入出力結果(Terminal)

ちゃんとハッシュを格納したログファイル(上記のプログラムのコードの場合はtotal_log.dat)も作成できてた!

0 コメント:

コメントを投稿