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.


Perl's payment curve coincides with its learning curve.

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
    Thanks a lot GrandFather..I'll use the code and try it out. Will let you all know. Appreciate your help.
      As per your requirement, will the transaction begin, only after end of the previous transaction? or when one transaction goes on, another transaction can be started? If it is, then you have to handle differently, your solution may not work, else this is fine.
        It will begin after the end transaction. So this should work.