我在标量中有一个类似2001:db8::1
的地址,并希望获得扩展形式2001:0db8:0000:0000:0000:0000:0000:0001
。主要的Perl软件包是否在/usr/lib/perl5/...
的广阔森林中运送 - 一个已经可以执行此操作的模块?如果没有,有人会有几行会这样做吗?
答案 0 :(得分:9)
CPAN Net::IP
可以满足您的需求。
这是一份成绩单,显示了它的实际效果:
$ cat qq.pl
use Net::IP;
$ip = new Net::IP ('2001:db8::1');
print $ip->ip() . "\n";
$ perl qq.pl
2001:0db8:0000:0000:0000:0000:0000:0001
答案 1 :(得分:2)
Net::IP
绝对是一个很好的方式,因为它简单而有力。但是,如果您要解析大量的问题,可以考虑使用inet_pton
包中的Socket
,因为它比Net::IP
对象版本快10-20倍,即使是预先创建的对象。比ip_expand_address
版快4倍:
use Net::IP;
use Time::HiRes qw(gettimeofday tv_interval);
use Socket qw(inet_pton AF_INET6);
use bignum;
use strict;
# bootstrap
my $addr = "2001:db8::1";
my $maxcount = 10000;
my $ip = new Net::IP($addr);
my ($t0, $t1);
my $res;
# test Net::IP
$t0 = [gettimeofday()];
for (my $i = 0; $i < $maxcount; $i++) {
$ip->set($addr);
$res = $ip->ip();
}
print "Net::IP elapsed: " . tv_interval($t0) . "\n";
print "Net::IP Result: $res\n";
# test non-object version
$t0 = [gettimeofday()];
for (my $i = 0; $i < $maxcount; $i++) {
$res = Net::IP::ip_expand_address('2001:db8::1', 6);
}
print "ip_expand elapsed: " . tv_interval($t0) . "\n";
print "ip_expand Result: $res\n";
# test inet_pton
$t0 = [gettimeofday()];
for (my $i = 0; $i < $maxcount; $i++) {
$res = join(":", unpack("H4H4H4H4H4H4H4H4",inet_pton(AF_INET6, $addr)));
}
print "inet_pton elapsed: " . tv_interval($t0) . "\n";
print "inet_pton result: " . $res . "\n";
在我的随机机器上运行这个:
Net::IP elapsed: 2.059268
Net::IP Result: 2001:0db8:0000:0000:0000:0000:0000:0001
ip_expand elapsed: 0.482405
ip_expand Result: 2001:0db8:0000:0000:0000:0000:0000:0001
inet_pton elapsed: 0.132578
inet_pton result: 2001:0db8:0000:0000:0000:0000:0000:0001