Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re^2: The return value of m// (clues)

by sophate (Beadle)
on Apr 23, 2012 at 05:25 UTC ( #966524=note: print w/ replies, xml ) Need Help??


in reply to Re: The return value of m// (clues)
in thread The return value of m//

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 ?


Comment on Re^2: The return value of m// (clues)
Select or Download Code
Re^3: The return value of m// (clues)
by quester (Vicar) on Apr 23, 2012 at 07:04 UTC

    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" }
Re^3: The return value of m// (clues)
by bimleshsharma (Beadle) on Apr 23, 2012 at 07:47 UTC

    Really i could not understand but the code

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

    is an issue.

Re^3: The return value of m// (clues)
by kcott (Abbot) on Apr 23, 2012 at 07:56 UTC

    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 :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://966524]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (9)
As of 2014-12-23 03:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (135 votes), past polls