Matching an array of strings to strings in a file.

Gianni Ceccarelli dakkar at thenautilus.net
Mon Aug 29 13:13:11 BST 2011


On 2011-08-29 "Martin A. Brooks" <martin at antibodymx.net> wrote:
> I have an array of strings.  I have some plain text files on disk.  I
> want to see if any of the lines in the text files contain any of the
> strings in the array.  I can stop as soon as I find one match.

#!perl
use Test::More;

sub look_in_file {
    my ($fh,$strings) = @_;

    my $rx = join '|',map { "\Q$_\E" } @$strings;
    $rx = qr{$rx};

    while (my $line = <$fh>) {
        #warn "<$line> =~ /$rx/\n";
        return 1 if $line =~ $rx;
    }
    return;
}

my $p=tell(DATA);
ok(look_in_file(\*DATA,[qw(foo bar baz)]));
seek DATA,$p,0;
ok(!look_in_file(\*DATA,[qw(not_there)]));
done_testing();

__DATA__
this line is useless
this one says bar
this one says foo, but should be ignored

-- 
	Dakkar - <Mobilis in mobile>
	GPG public key fingerprint = A071 E618 DD2C 5901 9574
	                             6FE2 40EA 9883 7519 3F88
	                    key id = 0x75193F88

 Hermes: Baby needs a new pair of shoes! 
 Zoidberg: To hell with your spoiled baby, I need those shoes. 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: not available
Url : http://london.pm.org/pipermail/london.pm/attachments/20110829/4cd4ca1d/signature.pgp


More information about the london.pm mailing list