in reply to Re^2: How can I test for the representation of an integer?
in thread How can I test for the representation of an integer?

One is a match and the other is a count - you can tell that from the different ways you have constructed the regex. By choosing a confusing value to test against makes this less obvious. Instead try with "2":

$ perl -MData::Dumper -e 'print Dumper("2" =~ /2/);' $VAR1 = 1; $ perl -MData::Dumper -e 'print Dumper("2" =~ /(2)/);' $VAR1 = '2';

Replies are listed 'Best First'.
Re^4: How can I test for the representation of an integer?
by haukex (Archbishop) on Apr 25, 2016 at 11:43 UTC

    Hi hippo,

    I think you're thinking of s///g, since m// doesn't return a count (perlop):

    $ perl -MData::Dumper -e 'print Dumper( "abbbbc"=~/b/ )' $VAR1 = 1; $ perl -MData::Dumper -e 'print Dumper( "abbbbc"=~/(b)/ )' $VAR1 = 'b'; $ perl -MData::Dumper -e 'print Dumper(scalar("abbbbc"=~/b/ ))' $VAR1 = 1; $ perl -MData::Dumper -e 'print Dumper(scalar("abbbbc"=~/(b)/ ))' $VAR1 = 1; $ perl -MData::Dumper -e 'print Dumper(scalar("abbbbc"=~/b/g ))' $VAR1 = 1; $ perl -MData::Dumper -e 'print Dumper(scalar("abbbbc"=~/(b)/g))' $VAR1 = 1; $ perl -MData::Dumper -e 'print Dumper( "abbbbc"=~/b/g )' $VAR1 = 'b'; $VAR2 = 'b'; $VAR3 = 'b'; $VAR4 = 'b'; $ perl -MData::Dumper -e 'print Dumper( "abbbbc"=~/(b)/g )' $VAR1 = 'b'; $VAR2 = 'b'; $VAR3 = 'b'; $VAR4 = 'b';

    To get a count you need to use the =()= trick (perlsecret):

    $ perl -MData::Dumper -e 'print Dumper(scalar(()="abbbbc"=~/b/g))' $VAR1 = 4; $ perl -MData::Dumper -e 'print Dumper(scalar(()="abbbbc"=~/(b)/g))' $VAR1 = 4;

    Regards,
    -- Hauke D

Re^4: How can I test for the representation of an integer?
by sm@sh (Acolyte) on Apr 25, 2016 at 11:14 UTC

    The regexps are user-supplied and arbitrary - they may or may not have captures.
    Matching the number '1' is a real use-case.

      So I guess you want the count rather than the match (since you didn't specify). In that case, just force scalar context:

      $ perl -MData::Dumper -e 'print Dumper(scalar ("2" =~ /(2)/));' $VAR1 = 1;

      Update: As per haukex's correction the scalar context simply forces true/false rather than the count of matches. The above strategy still applies if this (whether the regex is a match or not) is all that you really want to test.