my @lines = read_file('/tmp/test.txt'); chomp(@lines); my $sql = q|select * from table_name where srcaddr = ? or dstaddr = ?|; my $sth = $dbh->prepare($sql) or die "Can't prepare SQL statement: $DBI::errstr\n"; foreach my $line (@lines) { $sth->execute($line, $line) or die "Can't execute SQL statement: $DBI::errstr\n"; my @all_rows; while ( my $ref = $sth->fetchrow_arrayref()) { push(@all_rows, $ref); } my @sorted = map {$_->[0]} sort {$a->[1] <=> $b->[1] || $a->[2] <=> $b->[2] || $a->[3] <=> $b->[3] || $a->[4] <=> $b->[4]} map { [$_, split(/\./, (split /\s+/, $_)[1])]} @all_rows; print "$_\n" for @sorted; }