I watched @ikegami's answer, which turned out to be flawless, but I had no idea why. So I took a couple of points to understand the mechanics behind this, and I want to share my notes for future links for less experienced Perl experts ...
In this example, I chose two very specific IP addresses, because when encoded as ASCII, they will look like ABCD
and EFGH
, as seen on the output of the print Dumper()
.
The trick is to prefix each line of an IP address with 4 bytes containing its binary representation. Then the entries are sorted and finally the prefix is ββdeleted again, leaving a list of sorted IP addresses.
The internal works are described in the comments, it is best to read them in numbered order.
#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my @ips = qw( 69.70.71.72 65.66.67.68 ); print Dumper( map( pack( 'C4a*' , split( /\./ ) , $_ ) , @ips ) ); foreach my $ip ( map(
The output will look like this:
$VAR1 = 'EFGH69.70.71.72'; $VAR2 = 'ABCD64.65.66.67'; 64.65.66.67 69.70.71.72
If the first two lines are from print Dumper()
, which indicate that the IP addresses have a 32-bit prefix for representing numeric IP addresses.
source share