Hashを使ってユニークにしよう!

| 0 Comments | 1 TrackBack | このエントリーをはてなブックマークに追加 このエントリーのはてなブックマーク件数

皆さんHash使ってますか!


Hashを使うと、たくさんの重複したデータから、ユニークなデータだけを取り出すことが出来ます。

use strict;
use warnings;
use Data::Dumper;

my @cars = qw/honda honda suzuki toyota toyota daihatu mitubishia/;

my %report = ();
for my $car ( @cars ) {
        $report{ $car }++;
}

print Dumper \%report;

結果

$VAR1 = {
          'mitubishia' => 1,
          'toyota' => 2,
          'suzuki' => 1,
          'daihatu' => 1,
          'honda' => 2
        };

車を作ってるメーカが重複して入っている配列から、重複を取り除いたメーカを手に入れることができましたね!

実践例 : アクセスログから、ipの一覧と件数を取得する

武君のサーバは誰にも教えてないはずなのに、Webにアクセスがたまにきてることがわかりました。どのipから来てるのかしりたいので、調べることにしました。

#!/usr/bin/perl

use strict;
use warnings;
use IO::File;
use Data::Dumper;

my @files = @ARGV;
my %ips = ();
for my $file ( @files ) {
        my $fh = new IO::File;
        $fh->open( $file );
        while( <$fh> ) {
                my ( $ip ) = split(/\s/);
                $ips{$ip}++;
        }
        $fh->close;
}

print Dumper \%ips;

access_log , access_log.1 access_log.2 のような複数のファイルをチェックします。

 ./ips.pl access_log*

やったね!武君!

1 TrackBack

TrackBack URL: http://perl-mongers.org/MT/mt-tb.cgi/45

軽く便乗。 use strict; use warnings; use Data::Dumper; my @cars = qw/honda honda suzuki toyota toyota daihatu mitubishia/; my %report = (); for my $car ( @cars ) { $report{ $car }++; } print Dumper ¥%report; Hashを使ってユニークにしよう! - perl-mongers. Read More

Leave a comment

About this Entry

This page contains a single entry by tomyhero [livedoor.com] published on June 3, 2008 6:08 PM.

固定電話の市外局番一覧ページを csv にするお役立ち hack! was the previous entry in this blog.

perlでGUI is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Categories

Pages

Creative Commons License
This blog is licensed under a Creative Commons License.
Powered by Movable Type 4.21-en