OID or IP Address numeric sort


/ Published in: Perl
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. =head2 oidSort
  2.  
  3. Accepts an array or an array reference of Object Identifiers (OIDs) or
  4. IP addresses.
  5.  
  6. Returns a numerically sorted array or array reference, depending upon
  7. how the method is called. Returns 1 if nothing is passed, returns
  8. -1 if a reference to something other than an array is passed.
  9.  
  10. =cut
  11.  
  12. sub oidSort {
  13. my ( @oids, @_oids, $oid );
  14. my $self = shift;
  15. if ( !$_[ 0 ] ) {
  16. return 1;
  17. }
  18. elsif ( ref $_[ 0 ] eq "ARRAY" ) {
  19. @_oids = @{ $_[ 0 ] };
  20. }
  21. elsif ( !ref $_[ 0 ] ) {
  22. @_oids = @_;
  23. }
  24. else {
  25. return -1;
  26. }
  27. return @_oids if @_oids <= 1;
  28. @oids = map { $_->[ 0 ] }
  29. sort { $a->[ 1 ] cmp $b->[ 1 ] }
  30. map {
  31. my $oid = $_;
  32. $oid =~ s/^\.//;
  33. $oid =~ s/ /\.0/g;
  34. [ $_, pack 'N*', split m/\./, $oid ]
  35. } @_oids;
  36. return wantarray() ? @oids : \@oids;
  37. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.