468,507 Members | 1,587 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,507 developers. It's quick & easy.

How to sort IP address using perl script

3
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
May 30 '07 #1
4 9614
miller
1,089 Expert 1GB
Hello Ken,

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

Expand|Select|Wrap|Line Numbers
  1. my @ips = qw(
  2.     172.27.32.200
  3.     172.19.32.100
  4.     10.1.1.60
  5.     192.20.30.133
  6. );
  7.  
  8. @ips = map {s/\s+//g; $_} sort map {s/(\d+)/sprintf "%3s", $1/eg; $_} @ips;
  9.  
  10. print join "\n", @ips;
  11.  
  12. # Output is:
  13. # 10.1.1.60
  14. # 172.19.32.100
  15. # 172.27.32.200
  16. # 192.20.30.133
  17.  
- Miller
May 31 '07 #2
kk5151
3
Thanks Miller. This is excellent example

Thanks
May 31 '07 #3
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}


Expand|Select|Wrap|Line Numbers
  1. @ipaddress = ('172.27.32.200','10.1.1.60','192.20.30.133','172. 19.32.100');
  2. @ips=sort{$a<=>$b}(@ipaddress);
  3. foreach (@ips)
  4. {
  5. print "$_\n";
  6. }
Jan 22 '13 #4
HI Miller,

May I know what does
Expand|Select|Wrap|Line Numbers
  1. $1/eg
means here.

Expand|Select|Wrap|Line Numbers
  1. {s/(\d+)/sprintf "%3s", $1/eg; $_}
Mar 24 '16 #5

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by kelly | last post: by
3 posts views Thread by gieforce | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.