结合两个Perl脚本

时间:2017-04-08 00:17:37

标签: regex perl

此时,我正在使用两个perl脚本将文本文件转换为我想要的格式。一个perl脚本使用API​​从Web下载文件,将其存储为文件,然后仅打印IP地址(例如ips.txt) - 然后我将输出定向到另一个文本文件(例如perl script1.pl> ips2。文本)。打印输出如下所示:

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")

1 个答案:

答案 0 :(得分: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";