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?
Asked
Active
Viewed 4,067 times
2 Answers
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
-
-
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