in reply to Re^2: Multiple strings in a file
in thread Multiple strings in a file
It seems to me that the problem is not that you want to detect both strings, but that you want to print them in the order of precedence, even if that's not the order in which they appear in the file. So you already know what order you want; you want to see "trap" first, and "hair" second. But they appear in the file in such order that "hair" comes before "trap".
This means you should not print immediately upon finding a match. Instead, you should accumulate your matches, and then print them in the order of relevance or importance.
Is that what you're after? If so, let us know.
Update: Here's one way you can do that. We maintain a list of triggers in some order of precedence. We also construct a list of matches. Then we run through the matches in trigger-list-order, printing them out. If there are two lines that trip the same trigger, they will be printed in the order they were seen, but otherwise we maintain trigger order rather than file order. I think that's what you were looking for:
use strict; use warnings; my @order = qw( trap hair ); my %found; my $search = join '|', @order; while( <DATA> ) { if( m/($search)/i ) { chomp; push @{$found{lc $1}}, $_; } } foreach my $wanted ( @order ) { if( exists $found{$wanted} ) { print "$_\n" for @{$found{$wanted}}; } } __DATA__ Transformers robots in disguise I whip my hair back and forth I will catch a dog with a trap
The output:
I will catch a dog with a trap I whip my hair back and forth
As you can see, the output comes in the order that you set in @order. If there had been two lines that match the same trigger, however, those lines would maintain file-order. So first priority goes to trigger order, and then within trigger order, file order takes second priority.
Dave
|
|---|