in reply to Match a list of numbers from a list of files
The following code builds a string containing the current transaction and either prints it or throws it away depending on the state of a keep flag.
use strict; use warnings; my $numbers = join '|', qw(2345678923 2121212121 4424352424 2323232323 +); my $transaction = ''; my $keep; my $startRe = qr!<BEGIN Transaction>!; my $endRe = qr!</END Transaction>!; my $match = qr!(^|\D)($numbers)($|\D)!; while (defined (my $line = <DATA>)) { my $inTransaction = $line =~ $startRe .. $line =~ $endRe; next unless $inTransaction || $keep; $transaction .= $line; $keep ||= $line =~ /$match/sm; next unless $inTransaction =~ 'E0$'; print $transaction if $keep; $transaction = ''; $keep = undef; } __DATA__ <BEGIN Transaction> 2345678923 </END Transaction> <BEGIN Transaction> 1 </END Transaction> junk <BEGIN Transaction> 12345678923 </END Transaction> <BEGIN Transaction> 2121212121 </END Transaction>
Prints:
<BEGIN Transaction> 2345678923 </END Transaction> <BEGIN Transaction> 2121212121 </END Transaction>
Note the use of the flip-flop operator (..) to keep track of inside/outside the transaction and to detect the last line of the transaction.
Note also the use of qr to precompile the regular expressions that are used for matching transaction start/end and (more importantly) to match the numbers.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Match a list of numbers from a list of files
by shawshankred (Sexton) on Dec 18, 2008 at 00:53 UTC | |
by perlthirst (Scribe) on Dec 18, 2008 at 12:20 UTC | |
by shawshankred (Sexton) on Dec 18, 2008 at 18:31 UTC |