in reply to Trying to make a search Part 2


Cool. Thanx everyone. I finally got it like this:

#!/usr/bin/perl print "Search for what: "; chomp(my $search = <STDIN>); @words = split(/ /, $search); open(DATA, "books.txt") or die "error opening file $!"; while (<DATA>) { $matches=0; foreach $word(@words) { chomp($word); if (/$word/i) { print unless ($matches > 0); $matches++; } } }

-- zdog (Zenon Zabinski)
   Go Bells!!

Replies are listed 'Best First'.
RE: Re: Trying to make a search Part 2
by takshaka (Friar) on Jun 05, 2000 at 21:36 UTC
    One thing to note: The regex in your foreach loop has to be compiled several times (potentially) for every line, which can be a performance drain. A better approach is to precompile your regexes using the qr// operator (described in perlop).
    #!/usr/bin/perl print "Search for what: "; chomp(my $search = <STDIN>); @words = split(/ /, $search); # Turn words into regular expressions @words = map {qr/$_/i} @words; # If you don't want the user to have to # worry about regex syntax, use this instead: # @words = map {qr/\Q$_/i} @words open(DATA, "books.txt") or die "error opening file $!"; while (<DATA>) { $matches=0; foreach $word(@words) { if ($_ =~ $word) { print unless ($matches > 0); $matches++; } } }