2017-04-08 112 views
-1

在这一点上,我使用两个perl脚本将文本文件转换为我想要的格式。一个Perl脚本使用API​​从网上下载文件,将其存储为文件,然后仅打印IP地址(例如ips.txt) - 然后将输出导入另一个文本文件(例如,perl script1.pl> ips2.txt )。打印输出看起来是这样的:结合两个Perl脚本

222.187.221.224 
222.187.221.250 
222.187.239.35 
222.187.239.136 
222.215.230.79 
222.215.230.85 

第二脚本需要我创建更改IP地址为以下格式的文件:

("222.187.239.35" OR "222.187.239.136" OR "222.215.230.79" OR "222.215.230.85") 

我的问题是,我该如何最有效地结合这两种perl脚本合并为一个来执行所有必需的操作?文件创作是不必要的,这是我想出如何做到目前为止的唯一方法。非常感谢帮助。

第一脚本:

#/usr/bin/perl 

use strict; 
use warnings; 
use LWP::Simple; 
use Regexp::Common qw/net/; 

getstore("https://<redacted>", "ips.txt"); 


open(my $input, "<", "ips.txt"); 

while (<$input>) { 
    print $1, "\n" if /($RE{net}{IPv4})/; 
} 

第二脚本:

#!/usr/bin/perl 

use strict; 
use warnings; 
use LWP::Simple; 
use Regexp::Common qw/net/; 

open(my $input, "<", "ips2.txt"); 

print '(', join(' OR ', map { chomp; qq{"$_"} } grep { /$RE{net}{IPv4}/ } <$input>), ")\n"; 

希望的打印输出(有更多的IP地址,这只是一个例子):

("222.187.239.35" OR "222.187.239.136" OR "222.215.230.79" OR "222.215.230.85") 
+0

根据填充文件的方式,不需要grep {/ $ RE {net} {IPv4} /}'。 – ikegami

回答

1
use LWP::UserAgent qw(); 
use Regexp::Common qw(net); 

# Obviously incomplete, but good enough for IP addresses. 
sub text_to_lit { 
    my ($s) = @_; 
    return qq{"$s"}; 
} 

my $url = 'https://...'; 

my $ua = LWP::UserAgent->new(); 
my $response = $ua->get($url); 
$response->is_success() 
    or die("Can't download $url: " . $response->status_line() . "\n"); 

my $content = $response->content(); 

my @ips = $content =~ /^.*?($RE{net}{IPv4})/mg; # First per line 
    -or- 
my @ips = $content =~ /$RE{net}{IPv4}/g;   # All of them 

print "(".(join " OR ", map text_to_lit($_), @ips).")\n";