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

来源:互联网 发布:python 不包含字符串 编辑:程序博客网 时间:2024/05/15 04:30

同事写的简单的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();
}