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.
views:
267answers:
3
+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
2009-02-03 18:56:32
A:
Can you just use a string literal using q()?
print(q(This string can contain regex: (\n\t*\n)(\n)));
jcoon
2009-02-03 19:16:08
+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
2009-02-03 21:12:54