[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Using grep on a list of filenames.




  This is a general perl question, not a Mac specific question (so far as I know).

> Recently I was using grep in a function to check if a file in one directory
> has a cooresponding file in another directory in this way:
> 
> $InList=grep(/$filename/,@directorylist);
> 
> The function then returns $InList.  So far, this works great except in
> certain cases for reasons I don't quite understand.
> 
> I have one file named "1220-1220+21.56@2.D" which does contain a file of the
> same name in the other directory, yet the grep function will not catch it.
> If I rewrite the function using a foreach statement and compare $filename
> to every name in @directorylist, it works fine (but takes a lot longer, since
> I'm working on filesets containing more than 500 files each).

  Remember that the characters '+?.*^$()[]{}|\' have special meanings when they are a 
part of a regular expression.  By placing $filename between '//', you ask perl to 
interpret it as a regular expression, instead of as a straight string.  Try:
  
  $InList=grep("$filename",@directorylist);
  
instead.
  

  Regards,
  
  Daniel

PS.  If you want to see if a string contains characters that will be given special 
treatment by perl's RE mechanism, try:

  print STDOUT "$filename ". quotemeta $filename;
  
Any special characters will be prepended by a '\'.