Perl根据日期分割数据文件

Perl的优势:比C好写,比Shell高效,Linux普遍支持。

#!/usr/bin/perl -w
#    auth: lichmama@cnblogs.com
#    what: split data_file by date.

my $fullpath = $0;
my $script_name = sprintf "%s", $fullpath =~ /[^\/]*\.pl/g;
my $datafile;
my $destpath;
my $filename;
my $ARGC = scalar @ARGV;

if($ARGC<1 || $ARGC>2){
    die "Usage: $script_name [data_file] [dest_path]\n";
}else{
    $datafile = $ARGV[0];
    $filename = sprintf "%s", $datafile =~ /[^\/]*$/g;
    if($ARGC == 2){
        $destpath = $ARGV[1] . "/";
    }else{
        $destpath = sprintf "%s", $datafile =~ /([^\/]+\/)+/g;
    }
}

my %hash;

open(DATA, $datafile) or die "Error: cannot open file $datafile\n";
while(<DATA>){
    my $line = $_;
    my $date = substr($line, 0, 10);
    if(!$hash{$date}){
        open($hash{$date}, ">>$destpath$filename.$date.tmp") 
            or die "Error: cannot create file: $destpath$filename.$date.tmp\n";
    }
    print {$hash{$date}} $line;
}
close(DATA);

foreach my $fd (values(%hash)){
    close($fd);
}

 

posted @ 2015-03-30 15:15  lichmama  阅读(282)  评论(0编辑  收藏  举报