Since you provided your code and sample input and output data, I'll give you some code to get you started:
#!/usr/bin/env perl
use warnings;
use strict;
use Data::Dumper; # for debugging
$Data::Dumper::Useqq=1;
my $DEBUG = 1;
die "Usage: $0 <INPUT_FILE_ports> <INPUT_FILE_IP> <OUTPUT_FILE>"
if @ARGV!=3;
my ($PORTS_FILE, $IPS_FILE, $OUT_FILE) = @ARGV;
open my $ip_fh, '<:crlf', $IPS_FILE or die "$IPS_FILE: $!";
chomp( my @ips = <$ip_fh> );
close $ip_fh;
print Data::Dumper->Dump([\@ips], ['*ips']) if $DEBUG;
open my $out_fh, '>', $OUT_FILE or die "$OUT_FILE: $!";
open my $port_fh, '<:crlf', $PORTS_FILE or die "$PORTS_FILE: $!";
my $header = <$port_fh>;
while ( my $line = <$port_fh> ) {
chomp($line);
my ($line_nr,$rest) = $line =~ /^(\d+)(\s+.+)$/
or die "Failed to parse line: $_";
print Data::Dumper->Dump([$line_nr,$rest], [qw/line_nr rest/])
if $DEBUG;
die "Invalid line number: $line_nr"
if $line_nr < 1 || $line_nr > @ips;
my $ip = $ips[ $line_nr - 1 ];
print Data::Dumper->Dump([$ip], ['ip']) if $DEBUG;
print {$out_fh} $ip, $rest, "\n";
}
close $port_fh;
close $out_fh;
Note that this makes a few small assumptions:
- It doesn't validate the list of IP adresses. You could do that with, for example, Regexp::Common::net.
- This code assumes the ports list will always have a header line. If that's not always the case, you could check for the header line inside the while loop using a regular expression, perhaps in combination with the special variable $., and skip the current iteration of the loop with next.
- Because your code includes s/\r\n//, I am guessing that your input file has CRLF line endings and you're processing it on a *NIX OS. Adding the :crlf PerlIO layer will convert those CRLFs for you, so that's what I've done, and it'll leave a file that already has only LF line endings unchanged. The output file in this code will have LF line endings on *NIX, but you could also add the :crlf layer in that open as well to get CRLF.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.