saranperl has asked for the wisdom of the Perl Monks concerning the following question:

$s="boys are playing"; @a=$s=~/\w/; foreach(@a){ print $_."\n"; }
The above code. i got result 1 . Then ,if i change
@a=$s=~/\w+/
i will get 1 is answer. Then ,if i change
@a=$s=~/(\w)/
i will get b is answer. Then ,if i change
@a=$s=~/(\w+)/
i will get boys is answer. why answer is 1 without bracket ? why answer is b with bracket? please help me

Replies are listed 'Best First'.
Re: regex word return
by ig (Vicar) on Aug 27, 2009 at 05:49 UTC

    The answers to your questions are in Regexp Quote Like Operators but you might find perlretut a gentler introduction. You should take the time to read and become familiar with both of these and also with prelre.

    If the "/g" option is not used, "m//" in list context returns a list consisting of the subexpressions matched by the parentheses in the pattern, i.e., ($1, $2, $3...). (Note that here $1 etc. are also set, and that this differs from Perl 4’s behavior.) When there are no parentheses in the pattern, the return value is the list "(1)" for success. With or without parentheses, an empty list is returned upon failure.

    In your first two cases there are no parentheses and the pattern matches so the list "(1)" is returned. In the last two cases there is a pair of parentheses so the match returns a list consisting of what matched the enclosed pattern: a single character in the third case and a sequence of word characters in the fourth.

Re: regex word return
by jwkrahn (Abbot) on Aug 27, 2009 at 05:37 UTC
    why answer is 1 without bracket ?

    The match operator returns TRUE on success or FALSE on failure (1 or '') and since /\w/ matched it returns 1.

    why answer is b with bracket?

    A regular expression with capturing parentheses returns the contents of those capturing parentheses in list context so the first string that matches \w is returned.

    It looks like you may want to use the /g (global) match option:

    @a = $s =~ /\w/g;
Re: regex word return
by ikegami (Patriarch) on Aug 27, 2009 at 06:51 UTC

    If the pattern has three captures, it will return the three substrings it captured if successful.

    If the pattern has two captures, it will return the two substrings it captured if successful.

    If the pattern has one capture, it will return the substring it captured if successful.

    If the pattern has no captures, it will return nothing? No. You wouldn't be able to tell whether the match was successful or not if it returned nothing on both success and failure.

    So, if you want to capture something, you gotta tell it what you want it to capture.

Re: regex word return
by bichonfrise74 (Vicar) on Aug 27, 2009 at 05:40 UTC
    Basically, the ( ) captures the results that is why you get the b and boys as your answers. And the one where the answer is 1 simply says that it was able to match the regex properly. You might want to take a look at Regex for a better explanation.