By the way, what about when you get an address like 10.10.10.14 as the source? That'll sort before 10.10.10.5, so perhaps you should convert the IPs into 4-byte sequences.
When packed, the strings will be shorter and we could use the default { $a cmp $b } compare function. That makes the packed version much faster, and it would require less memory. Note the ingenious use of 0 or 1 to in lieu of $src.
print map { substr($_, 13) } sort map { my ($src, $dst) = (split)[0, 2]; $src = pack('C4n', split(/[.:]/, $src)); $dst = pack('C4n', split(/[.:]/, $dst)); $src lt $dst ? "$src${dst}0$_" : "$dst${src}1$_" } <DATA>;
Actually, adding $_ is redundant, since we can reconstruct it. The following would cut the memory usage in half:
print map { my @f = unpack('C4nC4na', $_); my $src = "$f[0].$f[1].$f[2].$f[3]:$f[4]"; my $dst = "$f[5].$f[6].$f[7].$f[8]:$f[9]"; ($src, $dst) = ($dst, $src) if $f[10]; "$src -> $dst\n" } sort map { my ($src, $dst) = (split)[0, 2]; $src = pack('C4n', split(/[.:]/, $src)); $dst = pack('C4n', split(/[.:]/, $dst)); $src lt $dst ? "$src${dst}0" : "$dst${src}1" } <DATA>;
Both of the above have been tested. They only work if the addresses are IPv4 addresses in dotted form.
By the way, if you have memory problems, you could use an external sort tool as follows:
{ open(local *TEMP, '>', $sort_input); while (<DATA>) { my ($src, $dst) = (split)[0, 2]; $src = pack('C4n', split(/[.:]/, $src)); $dst = pack('C4n', split(/[.:]/, $dst)); my $data = $src lt $dst ? "$src${dst}0" : "$dst${src}1"; print TEMP (unpack('H*', $data), "\n"); } } ...[ call external sort tool ]... { open(local *TEMP, '<', $sort_output); while (<TEMP>) { chomp; my @f = unpack('C4nC4na', pack('H*', $_)); my $src = "$f[0].$f[1].$f[2].$f[3]:$f[4]"; my $dst = "$f[5].$f[6].$f[7].$f[8]:$f[9]"; ($src, $dst) = ($dst, $src) if $f[10]; print("$src -> $dst\n"); } }
The convertion to hex is to avoid having newlines in your data.
In reply to Re^4: Sorting out troubles with advanced-ish sort
by ikegami
in thread Sorting out troubles with advanced-ish sort
by chargrill
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |