Hatena::Groupperl

Press::Alt_R

2010-07-07

Perlわかば (sort)

わかばと言いつつはまった(またpackで……)

#!perl

use strict;
use Benchmark qw(cmpthese);

my $DATA_FILE = "./ipaddr_list.txt";

# -- read fiile
open my $fh, "<" , $DATA_FILE ||die "cannot open file";
my @lines = <$fh>;
for (@lines) {chomp($_);}
close $fh;

# ---- sort lines via name.. but isn't it slow?

sub sort_via_names{
  my @sort_via_names = 
    map {$_->[0]}
      sort {ipstr_into_num($a->[1]) <=> ipstr_into_num($b->[1])}
        map {[$_, (split(":", $_))[1] ]}
          @lines;
  
  return @sort_via_names;
}

sub sort_via_names_cache{

  my @sort_via_names = 
    map {$_->[0]}
      sort {$a->[1] <=> $b->[1]}
        map {[$_, ipstr_into_num((split(":", $_))[1]) ]}
          @lines;
  
  return @sort_via_names;
}


sub ipstr_into_num{
  my $ipstr = shift;
  my $ipbin = pack('C4' , split(/\./ , $ipstr));
  my $ipnum = unpack('L', $ipbin);
  return $ipnum;
}

print join "\n" , sort_via_names() , "\n";

#cmpthese(1000, {nocache=>\&sort_via_names, cache=>\&sort_via_names_cache});

ポイント

  • sortの判定式の中はできるだけ軽く書かないといけませんよ