Perl按位并给我时髦的结果

时间:2011-09-19 23:20:49

标签: perl parsing ip bit-manipulation

我正在编写一个perl脚本来比较使用perls按位AND运算符的两个IP地址。但我得到了一些非常时髦的结果。我是perl的新手所以也许有人可以给我一些指示。

继承我的小剧本:

#!/usr/bin/perl

$address = "172.34.12.0";
$address2 = "255.255.255.0";

@octets = split (/\./,$address);
@octets2 = split (/\./,$address2);

#Funky results when doing a bitwise AND
#This outputs "050 24 00 0" What's going on here?
print $octets[0] & $octets2[0], "\n";
print $octets[1] & $octets2[1], "\n";
print $octets[2] & $octets2[2], "\n";
print $octets[3] & $octets2[3], "\n";

#Results are what I want when doing it as literals
#This outputs "172 34 12 0"
print 172 & 255, "\n";
print 34 & 255, "\n";
print 12 & 255, "\n";
print 0 & 0, "\n";

当在$ octets和$ octets2成员上执行按位AND时,任何人都知道为什么或如何获得“050 24 00 0”?当我按位和使用文字时,一切似乎都工作得很好。请帮忙。谢谢!

5 个答案:

答案 0 :(得分:13)

按位操作对字符串和数字的作用不同,split返回字符串。使用0+int将字符串转换为数字。 http://codepad.org/sqHntIgZ

#!/usr/bin/perl

$address = "172.34.12.0";
$address2 = "255.255.255.0";

@octets = split (/\./,$address);
@octets2 = split (/\./,$address2);

#Funky results when doing a bitwise AND
#This outputs "050 24 00 0" What's going on here?
print int($octets[0]) & int($octets2[0]), "\n";
print int($octets[1]) & int($octets2[1]), "\n";
print int($octets[2]) & int($octets2[2]), "\n";
print int($octets[3]) & int($octets2[3]), "\n";

#Results are what I want when doing it as literals
#This outputs "172 34 12 0"
print 172 & 255, "\n";
print 34 & 255, "\n";
print 12 & 255, "\n";
print 0 & 0, "\n";

答案 1 :(得分:6)

我建议您使用CPAN模块,例如Net :: IP。

也总是把 用严格; 使用警告; 在你的程序的顶部。

答案 2 :(得分:6)

如果你不打算使用像Net :: IP或Net :: Netmask这样的CPAN模块,至少要使用一些给你的工具:

use strict;
use warnings;
use Socket;

my $address = "172.34.12.123";
my $address2 = "255.255.255.0";

my $raw_masked = inet_aton($address) & inet_aton($address2);
my $masked = inet_ntoa($raw_masked);
print $masked, "\n";

或更简洁,简单地说:

use Socket;
print inet_ntoa(
  inet_aton("127.34.12.123") 
  & inet_aton("255.255.255.0") 
), "\n";

答案 3 :(得分:5)

这是一个可爱的快速版本:

my $address  = 172.34.12.0;
my $address2 = 255.255.255.0;
my @a = map ord, split //, $address & $address2;
say for @a;

要克服字符串化的字符串:

my $address  = eval "172.34.12.0";
my $address2 = eval "255.255.255.0";

答案 4 :(得分:4)

您没有转换为数字。你们正在将角色彼此联系起来。