http://www.perlmonks.org?node_id=961483

anasuya has asked for the wisdom of the Perl Monks concerning the following question:

Hi. I have a file, which looks similar to what I have provided below. I want to extract out CONSECUTIVE lines, which do not have NIL after the '=' sign.

1yxq_SWI_B_600 = c.55.1.1- 1grh_ADW_A_479 = NIL 1fm9_570_D_200 = a.123.1.1- 1ec1_BEE_A_501 = b.50.1.1- 1fm9_570_D_200 = a.123.1.1- 2zmh_NYA_A___1 = a.123.1.1- 1gvh_HQQ_A1398 = a.1.1.2-c.25.1.5- 1v9y_HDQ_A1140 = d.110.3.2- 1mqt_SPL_A_284 = NIL
Thus, I would want the output to look like this:
1fm9_570_D_200 = a.123.1.1- 2zmh_NYA_A___1 = a.123.1.1- 1gvh_HQQ_A1398 = a.1.1.2-c.25.1.5- 1v9y_HDQ_A1140 = d.110.3.2-
Please help. Thanks.

Replies are listed 'Best First'.
Re: restricting matching only to consecutive lines
by RichardK (Parson) on Mar 25, 2012 at 14:52 UTC

    Ok that seems simple enough. What have you tried? Show us your code and maybe we can help.

    Are the consecutive lines always in pairs ?

    or can there be more than two?

    Can you get a pair of lines where one of them '= NIL' ?

    and if you can, what do you want to happen?

    Oh well, that's enough questions for you to think about for now.

Re: restricting matching only to consecutive lines
by stevieb (Canon) on Mar 25, 2012 at 20:06 UTC

    Had a bit of fun with this. I'm sure there is a much shorter and better way, but alas, it is what it is :) Using your data:

    #!/usr/bin/perl use warnings; use strict; my @hold; my @data; while ( my $line = <DATA> ){ chomp $line; if ( $line =~ /NIL$/ || $line !~ /\w+/ ){ if ( scalar @hold > 1 ){ push @data, [ @hold ]; } undef @hold; next; } push @hold, $line; } for my $block ( @data ){ for my $entry ( @{ $block } ){ print "$entry\n"; } print "\n"; }

    EDIT: Fixed code so it would work with more than two consecutive lines.

      Thanks, stevieb.