Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

pattern match on entire file

by amulcahy (Acolyte)
on Nov 14, 2001 at 17:32 UTC ( [id://125304] : perlquestion . print w/replies, xml ) Need Help??

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

Hello All,

I want to search through a text file for a supplied pattern and if it exists -> do nothing. If not -> add the the text to the file.
The code I am using is:
$tempName= $query->param('searchText'); #user supplied open (FILE, "+>>filename"); @file = <FILE>; $temp = join('',@file); $temp =~ /$tempName/s; if ($temp eq '') { print FILE $tempName . "\n"; } close (FILE);
The format of the text in the file to be searched is like:


My problem is that the searchText is always added to the file as the search never seems to find anything.

Follow-up query:
For testing purposes I am only searching for "auto" but in the completed program I will be searching for the entire path. Will the inclusion of "/" in the search cause more problems, e.g. In the above code $tempName could be

$tempName = /home/Ireland/amu/amutest/


Replies are listed 'Best First'.
Re: pattern match on entire file
by CubicSpline (Friar) on Nov 14, 2001 at 18:26 UTC
    Howdy. You're almost there, it's just the way you're using the file that's giving you trouble. You should open the file once for reading, slurp in the @file array, close the file, and then open it again for appending (if necessary) to write the $tempName var. I'd think you'd want something like this:

    $tempName= $query->param('searchText'); #user supplied open (FILE, "filename"); @file = <FILE>; close FILE; $temp = join('',@file); $temp =~ /$tempName/s; if ($temp eq '') { open FILE, ">>filename"; print FILE $tempName . "\n"; } close (FILE);
Re: pattern match on entire file
by trantor (Chaplain) on Nov 14, 2001 at 18:31 UTC

    $temp =~ /$tempName/s;

    This searches for the string contained in $tempName in $temp, in multiline mode. It is not a problem if $tempName contains metacharacters because it will be interpolated only once.

    if ($temp eq '')

    This checks the contents of $temp, not the result of the pattern match!

    You should have now enough hints to go on :-)


      thank you trantor and CubicSpline - the combination of both worked.
      calree0 -> haven't tried grep yet, don't think speed is an issue for this but one never knows....

      thanks again...maybe someday I'll know enough to ask a question that might challenge you lot?
Re: pattern match on entire file
by claree0 (Hermit) on Nov 14, 2001 at 18:52 UTC
    If the user input is always going to be straight text rather than a regular expression, then it may be faster to use grep.
      You can shorten this:
      @file = <FILE>; $temp = join('',@file);
      to just one line:
      $file = join '', <FILE>;

      -tengo mas que aprender