Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, i have Question about using variables in RegEx and escaping characters in this variables.
I have a
$find_file = '/home/camel/file';
and a list of files with it size
@list_of_file = ('/home/camel/file 42', '/home/camel/file2 43', ...
and now i want to find the $find_file in @list_of_files if i try
foreach $line (@list_of_files){ if ($line =~ /$find_file/){ print ($line); } }
it can't find it, i think because of the not escaped slashes in $find_file
Have i to escape all regex control chars? Or is there an other way to do this?
Thanks
heinrich

Replies are listed 'Best First'.
Re: Using a Variable as a Match Expression
by wind (Priest) on Feb 16, 2011 at 17:45 UTC
    quotemeta or \Q..\E will fix your problem with special characters if you want to use a regex. Should probably add some boundary requirements though as well:
    foreach $line (@list_of_files){ if ($line =~ /^\Q$find_file\E\s/){ print ($line); } }
      Thanks!
Re: Using a Variable as a Match Expression
by ikegami (Patriarch) on Feb 16, 2011 at 17:30 UTC
    Use «use strict; use warnings;»!!
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Using a Variable as a Match Expression
by MidLifeXis (Monsignor) on Feb 16, 2011 at 17:46 UTC

    Personally, I would use a different data structure for your @list_of_file: %list_of_file = ( '/home/camel/file' => 42, ...); and then defined $list_of_file{$find_file}.

    However, given the data structures that you have, may I suggest looking at grep and index?

    --MidLifeXis