in reply to The return value of m//

Swap the positions in the file of the last two cases to get one clue. Once you've done that, print out what gets put into @a for another clue.

- tye        

Replies are listed 'Best First'.
Re^2: The return value of m// (clues)
by sophate (Beadle) on Apr 23, 2012 at 05:25 UTC

    Really interesting! I changed the script to:

    #!/usr/bin/perl use strict; use warnings; my $a=" 456 789 123 456 789 "; my $count; $count = $a =~ /\d+/g ; print "$count\n"; my @a = $a =~ /\d+/g ; $count = @a; print "@a\n"; print "$count\n"; $count = () = $a =~ /\d+/g ; print "$count\n";

    The results are:<\p>

    1 789 123 456 789 4 5

    Could you please advise why the 1st digit group is gone the first time i call $a =~ /\d+/g ?

      When you use the g modifier, it keeps track of its last match. In the first RE (scalar context), 456 is matched: your count indicates a single match (see code below for actual value). In the second RE (list context), the remaining four sets of digits are matched. You can use pos to reset the last match position.

      $ perl -Mstrict -Mwarnings -e ' > my $a=" 456 789 123 456 789 "; > my $count; > $count = $a =~ /\d+/g ; > print "$count\n"; > print "${^MATCH}\n"; > pos($a) = 0; > my @a = $a =~ /\d+/g ; > $count = @a; > print "@a\n"; > print "$count\n"; > ' 1 456 456 789 123 456 789 5

      ${^MATCH} is described in perlvar.

      -- Ken

        Thanks so much !! It's great to learn more about how g behaves :-)

      Hint: look for the phrase "search position" in perlop. Also consider that scalar global matches are typically used in loops, for example

      for my $match ($a =~ /\d+/g) { print "$match\n" }

      Really i could not understand but the code

      $count = $a =~ /\d+/g ; vs. $count = () = $a =~ /\d+/g ;

      is an issue.