11.46. Solution: Sort SNMP numbers

Example 11-18. examples/regex/sort_snmp_numbers.pl

#!/usr/bin/perl
use strict;
use warnings;

my $filename = shift or die "Usage: $0 filename\n";
open(my $fh, "<", $filename) or die "Could not open '$filename'\n";

my @snmps = <$fh>;
chomp @snmps;

print join "\n", @snmps;
print "\n------------------\n";
my @sorted_snmps = sort by_snmp_number @snmps;
print join "\n", @sorted_snmps;

sub by_snmp_number {
    my @a = split /\./, $a;
    my @b = split /\./, $b;
    foreach my $i (0..@a-1) { 
        return 1 if $i >= @b;
        next if $a[$i] == $b[$i];
        return $a[$i] <=> $b[$i];
    }
    return 0;
}

print "\n------------------\n";

my @data = map { {"ip" => $_, "data" => [split /\./, $_]} } @snmps; 
my @sorted_data = sort {g($a, $b)} @data;
my @sorted_snmps_take_two = map {$_->{ip}} @sorted_data;
print join "\n", @sorted_snmps_take_two;
print "\n------------------\n";


sub g {
    my ($a, $b) = @_;
    my @a = @{ $a->{data} };
    my @b = @{ $b->{data} };
    foreach my $i (0..@a-1) {
        return 1 if $i >= @b;
        next if $a[$i] == $b[$i];
        return $a[$i] <=> $b[$i];
    }
    return 0;
}

If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed