in reply to Catching multiple lines and assigning them as a single array element

while(<$fh>) reads the file line by line, so even with /sm the string that is tested for a match is either the line that contains the printf, or the line that contains the end ';' (if it spans over multiple lines). You can read the documentation on the input record separator: $/ which defines how much perl reads from a file on each iteration. By default the value of $/ is "\n" which will make perl stop everytime it sees an end of line. But you can also set it to undef to read (slurp) the whole file at once. Slurping will give wrong results though as the string:

printf(""); sleep(); print("");
will match only once because .* (with /s) will read the whole thing up to the last ;. Even line by line "printf(""); "printf(""); will only match once. One way to avoid that is to replace .* by .*? which means the shortest match possible (each time perl matches a new character it will try to stop the regex by looking for a ; before "eating" anything else with the dot)

In the best case scenario you can do something like:

{ local $/ = ";"; # local means perl will restore the value of $/ at t +he end of the block # and the default behaviour when reading a file for my $file (@files) { # Note the $!, which contains the reason for the opening failure open my $fh, '<', $file or warn "Coudn't open $file: $!\n"; while (<$fh>) # will stop at each ";", so read instruction by ins +truction { push @printfs, $1 if /(printf.*);/; } } }

Note that a case like printf(";"); will make your regex yield an unexpected result either with .*? or $/ = ";". This comes from the fact that C code is actually not a regular language, which means it can't be parsed by regular expressions. Luckily, perl regexes are far more powerful than simple regular expressions, even if the name seems to say otherwise. Making a foolproof C parser is still a really difficult (and kind of foolish) thing to do with regexes. So if you're quite sure of your input data and know it fits a certain pattern, you're probably safe with regexes, but if you notice you keep getting harder and harder to include exceptions, give up that path (what you would need then is a grammar parser).

Replies are listed 'Best First'.
Re^2: Catching multiple lines and assigning them as a single array element
by kort (Initiate) on Nov 03, 2015 at 20:25 UTC

    Thanks for the tips. I found that in my case a simple regex would do (of course I'm also finding idiotic comments in the multiline printfs sometimes, but that's something I was aware of from the beginning ;)). I have used: printf[^;]+; and found it does the job I wanted it to do ;)