如何使用Perl提取IP地址和端口号并进行比较

时间:2011-09-04 17:05:44

标签: perl

我有一个包含字符串中的端口号和IP地址的文件。我必须提取IP地址,根据公式计算端口号,并将其与文件中的端口号进行比较,并打印出不匹配的端口号。如果IP地址是W.X.Y.Z,则端口号的公式为50000 + 200(Y)+ Z. 文本文件具有以下格式。

exchangeA_5 = 53413; 239.189.17.13 7990

exchangeA_6 = 53415; 239.189.17.15 7990

exchangeA_e = 53470; 239.189.27.70 7990

exchangeA_5 = 53468; 239.189.27.68 7990

最好的方法是什么?

#!/usr/bin/perl
use strict;
use warnings;

open(my $fh, '<', 'fileC')
or die("Can't open fileC: $!\n");

while (<$fh>) {
    chomp;
    my ($key, $val) = split /=/;
    #print "$key\n";
    #print "$val\n";

    my ($port, $ip) = split /[;]/, $val;
    print "$port\n";
    print "$ip\n";

}

2 个答案:

答案 0 :(得分:4)

又快又脏:

perl -ne '($host, $port, @ip) = split /[=;.]/; print if $port != 50000+200*$ip[2]+$ip[3]' fileC

当然,你想把它改成一个很好的程序:)

答案 1 :(得分:0)

open(my $fh, '<', 'fileC.txt');
while (<$fh>) {
    chomp;
    if (!/^$/){
    ($Host,$port, @IP) =  split /[=;.]/;
    print "Host:$Host, IP:", (join '.',@IP),", and Port:$port\n";   
}}