Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Print multiple lines based on condition

by jcb (Parson)
on Mar 12, 2020 at 22:51 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2024-03-28 12:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found