Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

strange behavior of parenthesis

by mosh (Scribe)
on Jul 11, 2005 at 10:03 UTC ( [id://473884]=perlquestion: print w/replies, xml ) Need Help??

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

Hi Holly Monks !

I need an explanation of 2 similar code sections but with different results:

First one:

our $AUTOLOAD = "aaa::bbb::ccc"; my ($func) = $AUTOLOAD =~ /.*::(.*)$/; print "$func\n"; ## ccc print "$AUTOLOAD\n"; ## aaa::bbb::ccc
Second:
our $AUTOLOAD = "aaa::bbb::ccc"; my $func = $AUTOLOAD =~ /.*::(.*)$/; print "$func\n"; ## 1 print "$AUTOLOAD\n"; ## aaa::bbb::ccc
The only different between the 2 section of code is the parenthesis surrounded the $func

What's the explanation for it?

Thanks,
Mosh.

Replies are listed 'Best First'.
Re: strange behavior of parenthesis
by holli (Abbot) on Jul 11, 2005 at 10:12 UTC
    In list context the =~ operator returns the catched parts (those in between braces in the regex). In scalar context it returns the number of catched parts.

    The braces around $func induce list context. Should be clear now, no?


    holli, /regexed monk/
      Further to that, you can find this documented in perlop under the m/PATTERN/cgimosx subsection of the Regexp Quote-Like Operators section:
      If the /g option is not used, perlop in a 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.
      HTH

      _________
      broquaint

      So, it catches only the (.*) ?
      How come ?

        So, it catches only the (.*) ?

        What else?

        Dodge This!
Re: strange behavior of parenthesis
by ysth (Canon) on Jul 11, 2005 at 15:49 UTC
    This is a scalar assignment, and the right side is evaluated in scalar context:
    $foo = ...
    These are list assignments, and the right side is evaluated in list context:
    ($foo) = ... @foo = ... %foo = ... @foo{LIST} = ... @foo[LIST] = ... () = ...
    What the match operator returns depends on success of the match, context, presense of capturing parenthesis, and whether there's a //g flag. See the doc for details.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://473884]
Approved by fxmakers
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (2)
As of 2024-04-20 03:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found