in reply to Re: Question on RE based matching
in thread Question on RE based matching

Hi ww,
Here is the complete code:
#!/usr/bin/perl use strict; use warnings; our ($fileIn, $fileOut); use Getopt::Long; GetOptions( 'FileIn=s' => \$fileIn, 'FileOut=s' => \$fileOut, ); if($fileIn && $fileOut) { open(INPUT,"<","$fileIn"); #undef $/; while(<INPUT>) { next if /^\n/; s/\t+//g; s/^\s+//g; if(/^HEADER(.*?)^GENRE_BY(.*)/sm) { print ; } } }

I saved this code into a file called x.pl. Made x.pl into an excutable code.
I executed, ./x.pl -fileIn lla -fileOut out_file
where the input file lla contains:
HEADER( LIBDAT("GTASK") VENDOR("DeltaQ") Environment("zeronom") TASK_VERSION("5.2") GENRE_BY("dumpTc") ) ... ... HEADER( LIBDAT("GTASK") VENDOR("DeltaQ") Environment("zeronom") TASK_VERSION("5.2") GENERATED_BY("dumpTc") ) ... ... HEADER( LIBDAT("GTASK") VENDOR("DeltaQ") Environment("zeronom") TASK_VERSION("5.2.1") GENRE_BY("dumpTc") ) ... ...

I am possibly doing something wrong. Any help will be great!
Christina J.

Replies are listed 'Best First'.
Re^3: Question on RE based matching
by almut (Canon) on Nov 19, 2007 at 10:12 UTC

    Your (main) problem is that you're matching against individual lines, i.e. 'HEADER(', next '  LIBDAT("GTASK")', and so on. In other words, the regex can never find 'HEADER...' and 'GENRE_BY...' at the same time.

    One way around this would be to split the input appropriately (as shown in the snippet by GrandFather). Another way would be to use the flip-flop operator .. to accumulate the necessary lines as shown below. The expression if (/^HEADER/ .. /^\)/) is true starting with a line matching /^HEADER/ up until a line matching /^\)/, in which case you append the current line to the accumulator ($entry). Upon the next line (not being HEADER or )) the flip-flop is reset to false.

    (I've put in an additional end-of-entry test (if (/^\)), so the code will correctly deal with the case where a new HEADER line is immediately following a previous entry (without any other lines in between) — if your input always has other stuff in between the entries, you could also just put the regex test directly in an else branch of the flip-flop test...)

    #!/usr/bin/perl use strict; use warnings; use Getopt::Long; GetOptions( 'FileIn=s' => \my $fileIn, 'FileOut=s' => \my $fileOut, ); if ($fileIn && $fileOut) { open(INPUT,"<","$fileIn"); my $entry = ""; while (<INPUT>) { next if /^\n/; if (/^HEADER/ .. /^\)/) { # flip-flop $entry .= $_; # accumulate input } if (/^\)/) { # end of entry # check for desired type of entry if ($entry =~ /^HEADER(.*?)^\s*GENRE_BY(.*)/sm) { print $entry; } $entry = ""; # reset accumulator } } }