andy andy - 6 months ago 17
Perl Question

Parsing irregular command's output in perl

I'm quite new to Perl and I'm having immense difficulty writing a Perl script that will successfully parse a structured text file.

Basically the file includes text similar to these:

//test/some_text/value1
... #001 some non important text
... #023 some non important text
//test/some_text/value2
... #1123 some non important text
//test/some_text/value3
... #001 some non important text
... #023 some non important text
... #022 some non important text
... #566 some non important text
//test/some_text/value4
... #42 some non important text


Unfortunately I can not predict how many lines with dots I will have bellow each of line started with // and I would like to get the output like this:

//test/some_text/value1 - 001
//test/some_text/value1 - 023
//test/some_text/value2 - 1123
//test/some_text/value3 - 001
//test/some_text/value3 - 023
//test/some_text/value3 - 022
//test/some_text/value3 - 566
//test/some_text/value4 - 42


I'm reading text file line by line but I feel that it isn't best solution. I would really appreciate your hints and help with solving the problem.

Answer

Line-by-line is OK. You just need to store the prefix line.

use warnings;
use strict;

my $prefix;
while (<DATA>) {
    if (m{^//}) {
        chomp;
        $prefix = $_;
    }
    else {
        my ($num) = /#(\d+)/;
        print "$prefix - $num\n";
    }

}

__DATA__
//test/some_text/value1
... #001 some non important text
... #023 some non important text
//test/some_text/value2
... #1123 some non important text
//test/some_text/value3
... #001 some non important text
... #023 some non important text
... #022 some non important text
... #566 some non important text
//test/some_text/value4
... #42 some non important text