10
my @matches = ($result =~ m/INFO\n(.*?)\n/);

So in Perl I want to store all matches to that regular expression. I'm looking to store the value between INFO\n and \n each time it occurs.

But I'm only getting the last occurrence stored. Is my regex wrong?

Takkun
  • 6,131
  • 16
  • 52
  • 69
  • possible duplicate of [How can I find all matches to a regular expression in Perl?](http://stackoverflow.com/questions/1723440/how-can-i-find-all-matches-to-a-regular-expression-in-perl) – centic Jun 22 '15 at 08:48

1 Answers1

14

Use the /g modifier for global matching.

my @matches = ($result =~ m/INFO\n(.*?)\n/g);

Lazy quantification is unnecessary in this case as . doesn't match newlines. The following would give better performance:

my @matches = ($result =~ m/INFO\n(.*)\n/g);

/s can be used if you do want periods to match newlines. For more info about these modifiers, see perlre.

Tim
  • 13,904
  • 10
  • 69
  • 101
  • Why `/s` is needed? I see no reason for that, as his match **should not** contain any new-line character(s). – Ωmega Jun 26 '12 at 14:03
  • You're right that it doesn't matter in this case, but since he didn't knew about `/g` and was matching multi-line strings, it seemed reasonable that he would need `/s` sooner or later. – Tim Jun 26 '12 at 14:06
  • 1
    `m/INFO\n(.*)\n/g` would be quicker but also less similar to OP's original try. – Tim Jun 26 '12 at 14:07
  • You should update your answer with this one :) You can still add some notes to your answer to give OP a lessons about `/g` and `/s`, sure... – Ωmega Jun 26 '12 at 14:10