You are very close: you need to move the my $address out of the loop so the value is remembered across iterations.

Example: (untested)

my $address; while (<IN_FILE>) { $address = hex $1 if m/address:([-[:xdigit:]]+)\s+/; next unless defined $address; if ($address & 1) { print OUT_FILE1 $_ } else { print OUT_FILE2 $_ } }

This is a very basic finite state machine. The $address lexical holds state (the most recent address seen) across loop iterations. There are a few other changes as well. First, the builtin $_ is used instead of a lexical to hold the input line; since pattern matches also default to using this variable, some clutter can be removed. Second, the address value capture is combined with the test for its presence and the statement modifier form is used. Third, no output is produced until an address has been seen (the next unless defined $address provides this feature). Lastly, the address is being stored as an integer, so an integer bit test is used instead of converting it back to a string.


In reply to Re: Print multiple lines based on condition by jcb
in thread 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.