Hi Monks,

I am trying to divide one huge file into two files using perl. My source file is something like this

######## file ########

1. command:read address:0xA

2. command:write address:0xB

3. writedata:0x12

4. writedata:0x34

5. writedata:0x56

6. writedata:0x78

7. command:read address:0xC

8. command:write address:0xD

9. writedata:0x9A

10. writedata:0xBC

11. writedata:0xDE

12. writedata:0xF0

######## file ########

Taking the above file as input I want to split the content into two different files based on address[0]=0/1. If address[0]=1, I want to print that line to one.txt else print that line to zero.txt no matter whether it is write/read. There is no problem to handle lines of read as it has only one line but the issue here is every write command is followed by next 4 lines of write data. How to print 4 write data lines followed by every write command line to both the output files.

######## code starts ######## while (my $line1 = <IN_FILE>) { if( ($line1 =~ /address/) ) { $line1 =~ /address:([a-z0-9-]+)\s+/; my $address = hex $1; $grep = substr( (sprintf "%b", $address), -1, 1); if($grep) { printf OUT_FILE1 ("$line1"); } else { printf OUT_FILE2 ("$line1"); } } } ######## code ends ########

I am struggling here for printing 4 write data lines because my while loop iterates per line and if I am using any loop inside my while loop to print the $line1 variable 4 times then it's printing the same line for 4 times


In reply to Print multiple lines based on condition by syedasadali95

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.