基于第三列对数据进行排序

时间:2011-03-17 00:43:32

标签: perl

AAAAAAAA    0.0.0.0   hs01.stuff.net
BBBBBBBB    0.0.0.0   hs01.morestuff.net
CCCCCCCC    0.0.0.0   hs01.evenmorestuff.net
DDDDDDDD    0.0.0.0   hs01.stuff.net
EEEEEEEE    0.0.0.0   hs01.stuff.net
FFFFFFFF    0.0.0.0   hs01.evenmorestuff.net
GGGGGGGG    0.0.0.0   hs01.stuff.net
HHHHHHHH    0.0.0.0   hs01.evenmorestuff.net

我一直在寻找,但我找不到我要找的答案。

如何按上面输出的第3列排序?

这是我的代码:

#!/usr/local/bin/perl
use warnings;
use DBI;
use DBD::Oracle;
use HTML::Template;
use List::MoreUtils 'uniq';

######################### Open File and Split The Data Into An Array ####################################
$input_data_file = 'C:\wamp\www\input_corrolation_file.txt';
open (DAT, $input_data_file)
      or die ("Could not open file!");

@raw_data = <DAT>;

close(DAT);
#########################################################################################################


$dbh_source2 = DBI->connect("dbi:Oracle:host=????;port=????;sid=????",'????','????');
$SEL = "SELECT DISTINCT PE_LOOPBACK_IP,PE_FQDN FROM TABLE_NAME WHERE SITE_NAME = ?";
$sth = $dbh_source2->prepare($SEL);
print '<table border=1>';
print '<tr>';
print '<th>Tower name</th>';
print '<th>SUR IP</th>';
print '<th>SUR FQDN</th>';
print '</tr>';



foreach my $data_line (@raw_data) {
        chomp $data_line;
       $sth->execute($data_line);

        my @row = $sth->fetchrow_array;
        unshift (@row, $data_line);
              #Print data into cells#
              print "<tr>";
              foreach (@row) {
                print "<td>$_</td>";
              }
              print "</tr>";
              #print "<$data_line>\t @row\n";



}

print "</table>";
END {
            $dbh_source2->disconnect if defined($dbh_source2);
}

那么我怎样才能在第三列的@row中对数据进行排序?

感谢所有帮助!

2 个答案:

答案 0 :(得分:2)

将提取与数据库和打印分开,并在打印前进行排序:

my @rows;
foreach my $data_line (@raw_data) {
    chomp $data_line;
    $sth->execute($data_line);

    my @row = $sth->fetchrow_array;
    unshift (@row, $data_line);
    push @rows, \@row;
}

@rows = sort { $a->[2] cmp $b->[2] } @rows;

foreach my $row (@rows) {
    print "<tr>";
    foreach (@$row) {
        print "<td>$_</td>";
    }
    print "</tr>";
}

答案 1 :(得分:0)

您可以将表放入散列中,其中键是行,值是要排序的字段的值,然后按值对散列进行排序:

my @arr;
my @sorted_arr;
my $key;
my %hash_sort;
my @broken_line;

push (@arr,"last\t222222\tzrf.bcd.cde");
push (@arr,"first\t999999\tabc.poi.pko");
push (@arr,"second\t444444\tjko.drt.xdf");
push (@arr,"third\t111111\tmno.lkn.tyf");

foreach $key (@arr){
  # print "$key\n";
  @broken_line = split("\t",$key);      
  $hash_sort{$key}=$broken_line[2];
}

foreach $key (sort {$hash_sort{$a} cmp $hash_sort{$b}} (keys(%hash_sort))){
  print "$key\n";
  push (@sorted_arr,$key);
}

此代码创建一个新的排序数组,并打印排序的行。