How to sort IP address using perl script

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kk5151
    New Member
    • May 2007
    • 3

    How to sort IP address using perl script

    Hi,

    Would like to learn and know how to sort the ip address using perl script?

    For example:
    172.27.32.200
    172.19.32.100
    10.1.1.60
    192.20.30.133

    @ipaddress = ('172.27.32.200 ','10.1.1.60',' 192.20.30.133', '172.19.32.100' );

    Don't know what to do next?

    thanks,
    Ken
  • miller
    Recognized Expert Top Contributor
    • Oct 2006
    • 1086

    #2
    Hello Ken,

    There are likely lots of different ways to accomplish this, but here is one that I think is particularly cute.

    [CODE=perl]
    my @ips = qw(
    172.27.32.200
    172.19.32.100
    10.1.1.60
    192.20.30.133
    );

    @ips = map {s/\s+//g; $_} sort map {s/(\d+)/sprintf "%3s", $1/eg; $_} @ips;

    print join "\n", @ips;

    # Output is:
    # 10.1.1.60
    # 172.19.32.100
    # 172.27.32.200
    # 192.20.30.133
    [/CODE]

    - Miller

    Comment

    • kk5151
      New Member
      • May 2007
      • 3

      #3
      Thanks Miller. This is excellent example

      Thanks

      Comment

      • perlbabu
        New Member
        • Jan 2013
        • 1

        #4
        Hello Ken,
        we can do many ways so here is to sort based on numeric

        sort is by default based on strings but if you want to sort based on number in perl
        syntax:sort{$a <=>$b}


        Code:
        @ipaddress = ('172.27.32.200','10.1.1.60','192.20.30.133','172. 19.32.100');
        @ips=sort{$a<=>$b}(@ipaddress);
        foreach (@ips)
        {
        print "$_\n";
        }
        Last edited by Rabbit; Jan 22 '13, 04:21 PM. Reason: Please use code tags when posting code.

        Comment

        • thakar86
          New Member
          • Mar 2016
          • 1

          #5
          HI Miller,

          May I know what does
          Code:
          $1/eg
          means here.

          Code:
          {s/(\d+)/sprintf "%3s", [B]$1/eg[/B]; $_}

          Comment

          Working...