3

How can I read from am file and find the matched patterns into a file not line by line to whole file at one time with Perl?

kamaci
  • 72,915
  • 69
  • 228
  • 366
  • 2
    See http://stackoverflow.com/questions/206661/what-is-the-best-way-to-slurp-a-file-into-a-string-in-perl – Wooble Apr 13 '11 at 17:41

2 Answers2

3

Read the whole file into a string, by adding the local $/; handle to the beginning of the perl script before reading the file. They you can apply your regex to the resulting string.

Once you build the long $string which contains the whole file, you can find all the matches as follows:

@matches = $string =~ m/\s*rem/gi;
Pirooz
  • 1,268
  • 1
  • 13
  • 24
  • For example my string variable is $string, and my regex patter is m/\s*rem/i so how can I find all the matched string according to that pattern and if possible while writing it to output putting a newline - \n after every matched string? – kamaci Apr 13 '11 at 17:58
  • For matching all, you need to add `g` modifier. Do your matching like this: `@matches = $string =~ m/\s*rem/gi;` – Pirooz Apr 13 '11 at 18:04
  • How can I remove newline characters with modifying my pattern? – kamaci Apr 13 '11 at 18:34
  • substitute all the newlines with blank `$string =~ s/\n*//g;` – Pirooz Apr 13 '11 at 18:44
3

I know this is old, but I was faced with the same problem and found the answer to be simpler than the chosen answer. Using '-0777' (or anything larger than -0400) toghether with -p or -n after the perl executable will change the default separator and perl will slurp the whole file into $_

References:

Radu C
  • 303
  • 2
  • 11