Reputation: 1
I have a long IPv6 address in a scalar like
2001:0db8:0:0:0:0:0:0
and would like to get the compact notation:
2001:db8::.
Does the main Perl package /usr/lib/perl5/...
contain a module that will do this?
Does the Net::IP module?
If not, does someone have a few lines that would do this?
Sort of the opposite of what Net::IP::ip_expand_address does.
Upvotes: 0
Views: 979
Reputation: 1578
The NetAddr::IP
module offers the short
method to do just that.
example:
#!/usr/bin/env perl
use strict;
use warnings;
use NetAddr::IP;
my $ip = NetAddr::IP->new( '2001:0db8:0:0:0:0:0:0' );
print "Long version: " . $ip->addr . "\n";
print "Short/Compact version: " . $ip->short . "\n";
Upvotes: 2
Reputation: 54371
The module IPv6::Address can do that when you call its addr_string
method, but it's not in core. However, you can borrow the code that does it fairly quickly.
All I did was take the part that creates the compact notation, and wrap it in a sub
.
sub compact {
# taken from IPv6::Address on CPAN
my $str = shift;
return '::' if($str eq '0:0:0:0:0:0:0:0');
for(my $i=7;$i>1;$i--) {
my $zerostr = join(':',split('','0'x$i));
###print "DEBUG: $str $zerostr \n";
if($str =~ /:$zerostr$/) {
$str =~ s/:$zerostr$/::/;
return $str;
}
elsif ($str =~ /:$zerostr:/) {
$str =~ s/:$zerostr:/::/;
return $str;
}
elsif ($str =~ /^$zerostr:/) {
$str =~ s/^$zerostr:/::/;
return $str;
}
}
return $str;
}
print compact('2001:0db8:0:0:0:0:0:0');
This will print
2001:0db8::
It seems to be ok with already compacted strings too.
Upvotes: 0