in reply to /g matches not really global in scalar context!

The reason behind this behaviour of /g (returning only one match at a time) becomes even more clear to me with a for loop:
use warnings; use strict; my $x = "aiutino aiutino argh! aiutino"; warn "Argh, one time" for $x =~ / \b aiutino \b /ix; warn "Argh, three times" for $x =~ / \b aiutino \b /gix;
jonix

Replies are listed 'Best First'.
Re^2: /g matches not really global in scalar context!
by Aristotle (Chancellor) on Nov 14, 2005 at 14:04 UTC

    Don’t confuse yourself. foreach puts its expression into list context, so a /g match actually returns a list of all matches at once; of course the foreach then iterates over them one by one. The loop construct you want is while, which evaluates its condition in scalar context, so a /g match as the condition will return matches one by one.

    Makeshifts last the longest.

      Thanks for making this clear. Is there a way to get all those /g matches at once without a loop?
      OK just found it:
      use warnings; use strict; my $x = "aiutino aiutino argh! aiutino"; my @matches = $x =~ / \b aiutino \b /gix; print "$_\n" for @matches;
      so it is depending on scalar vs. list context what you will get.
      Thanks again,
      jonix
Re^2: /g matches not really global in scalar context!
by blazar (Canon) on Nov 14, 2005 at 14:31 UTC

    Huh?!?

    I think you misunderstood me! I do use very often the /g modifier in list context:

    my $n =()= / \b aiutino \b /gix; warn "Argh, $n times";
    or
    warn "$_ => Argh!\n" for / \b aiutino \b /gix; # Ok: not that interesting with a fixed lenght string!

    Update: in the code above I did s/smart/interesting/, as per Aristotle's remark: indeed the latter adjective better reflects my feeling - I meant that $_ saves me some typing but will always have the value 'aiutino', and it would be more interesting with a more complex regex. Well, thinking of it better, not quite always 'aiutino', because I used /i, but still there ought to be more interesting cases...

      not that smart with a fixed lenght string!

      Why not? Firstly, you’re using \b, which condition you’d have to code manually if you were to use a string search – that would require a lot of extra code and would be slower. Secondly, the regex engine is smart enough to do a simple string search itself when it sees simple patterns like yours.

      So absolutely, you should use a pattern for the job you’re after.

      Makeshifts last the longest.