您的位置:首页 > 编程语言

Perl 使用 sort, hash解析文件代码

2011-07-18 18:03 246 查看
同事写的简单的Perl代码

#!/usr/bin/perl -w
use strict;

my $pbid_index = 0;
my $lbid_index = 3;
my $ver_index = 5;
my $uuid_index = 6;

&test();

sub my_sort {
my %hash;
my @keys;
my @sorted_keys;
my $uuid;
my $last_uuid;

open(M_FILE, "<middlefile");
#read files
while (<M_FILE>) {
my @file_line = split(/:/);
my $logid = $file_line[$lbid_index];
my $flag = -1;

if ($file_line[$pbid_index] ne "pbid") {
next;
}

#find uuid

$uuid = $file_line[$uuid_index];
if (!$uuid) {
next;
} elsif (!$last_uuid) {
$last_uuid = $uuid;
} elsif (eof || ($last_uuid ne $uuid)) {
#sort file
@keys = keys %hash;
@sorted_keys = sort {$a <=> $b} @keys;

#open new file
open NEW_FILE, '>file_'.$last_uuid;

#write files
foreach (@sorted_keys) {
print NEW_FILE $hash{$_};
}

#close files
close NEW_FILE;
$last_uuid = $uuid;
undef %hash;
undef @keys;
undef @sorted_keys;
}

if (exists $hash{$logid}) {
my $new_ver = hex($file_line[$ver_index]);
my @old_line = split(/:/, $hash{$logid});
my $old_ver = hex($old_line[$ver_index]);

if ($new_ver > $old_ver) {
$hash{$logid} = $_;
}
} else {
$hash{$logid} = $_;
}
}

close M_FILE;
}

sub sort_uuid {
my $uindex = 7;
my $cmd = "sort -d -t : -k $uindex -o middlefile tmp";
my $TMP;
my @line;

print $uindex;
open $TMP, '>tmp';
while (<>) {
@line = split(/:/);
if ( 'pbid' ne $line[0]) {
next;
}
print $TMP $_;
}

close $TMP;

system($cmd);
system('rm -f tmp');
}

sub test {
&sort_uuid();
&my_sort();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: