views:

267

answers:

3

I have a file that I want to read in using the File::Slurp module then search that file for a specific line. I know Perl has regular expressions but the strings I’m searching for are user-generated so don’t want to have to worry about escaping everything. I could write a foreach loop to do this but was wondering if there’s a function in Perl that will do this for me? Everything I see online about finding text in Perl uses regular expressions.

+16  A: 

You can just use a regular expression. You don't have to worry about escaping everything, Perl has the quotemeta function for that (or alternatively, "\Q\E").

Leon Timmermans
A: 

Can you just use a string literal using q()?

print(q(This string can contain regex: (\n\t*\n)(\n)));
jcoon
+2  A: 

Like this?

use List::Util qw<first>;

my $line 
    = first { index( $_, $something_users_are_looking_for ) > -1 } 
      <$file>
    ;

And if you want 'em all.

my @lines
    = grep { index( $_, $something_users_are_looking_for ) > -1 } 
      <$file>
    ;
Axeman