Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Print multiple lines based on condition

by jcb (Priest)
on Mar 12, 2020 at 22:51 UTC ( #11114194=note: print w/replies, xml ) Need Help??

in reply to Print multiple lines based on condition

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.

Replies are listed 'Best First'.
Re^2: Print multiple lines based on condition
by syedasadali95 (Acolyte) on Mar 13, 2020 at 06:34 UTC

    Thanks everyone for your support and suggestions. Now I know that there are multiple ways of doing this task. It seems to me that the simplest way to do it is by using state machine. Thanks again guys!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11114194]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2020-05-28 21:56 GMT
Find Nodes?
    Voting Booth?
    If programming languages were movie genres, Perl would be:

    Results (166 votes). Check out past polls.