Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

restricting matching only to consecutive lines

by anasuya (Novice)
on Mar 25, 2012 at 14:15 UTC ( #961483=perlquestion: print w/ replies, xml ) Need Help??
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.

Comment on restricting matching only to consecutive lines
Select or Download Code
Re: restricting matching only to consecutive lines
by RichardK (Priest) 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 (Hermit) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://961483]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (10)
As of 2014-10-31 08:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (215 votes), past polls