Return to Snippet

Revision: 61336
at December 6, 2012 14:43 by kurtkincaid


Initial Code
=head2 oidSort

Accepts an array or an array reference of Object Identifiers (OIDs) or 
IP addresses. 

Returns a numerically sorted array or array reference, depending upon 
how the method is called. Returns 1 if nothing is passed, returns 
-1 if a reference to something other than an array is passed.

=cut

sub oidSort {
    my ( @oids, @_oids, $oid );
    my $self = shift;
    if ( !$_[ 0 ] ) {
        return 1;
    }
    elsif ( ref $_[ 0 ] eq "ARRAY" ) {
        @_oids = @{ $_[ 0 ] };
    }
    elsif ( !ref $_[ 0 ] ) {
        @_oids = @_;
    }
    else {
        return -1;
    }
    return @_oids if @_oids <= 1;
    @oids = map { $_->[ 0 ] }
        sort { $a->[ 1 ] cmp $b->[ 1 ] }
        map {
        my $oid = $_;
        $oid =~ s/^\.//;
        $oid =~ s/ /\.0/g;
        [ $_, pack 'N*', split m/\./, $oid ]
        } @_oids;
    return wantarray() ? @oids : \@oids;
}

Initial URL


Initial Description
I love this one. Needed a good way to numerically sort IP addresses or OIDs. Took longer to come up with this than I'm willing to admit. Hope others find it useful.

Initial Title
OID or IP Address numeric sort

Initial Tags
sort, perl

Initial Language
Perl