UnitasBrooks
UnitasBrooks

Reputation: 1092

Why do you need parenthesis to save the result of a regular expression in Perl?

Why does this return the string between foo and bar:

my ($var) = $my_string =~ /foo(.*)bar/;

And this return the number 1 if there is a hit and nothing if there is no match:

my $var = $my_string =~ /foo(.*)bar/;

Specifically what are the parenthesis around the variable doing?

Upvotes: 2

Views: 119

Answers (3)

Hunter McMillen
Hunter McMillen

Reputation: 61540

As with many things in Perl, the result of that expression is different based on the context that is put in.

The pattern match operator will return a list of captures in list contact (your first example). If the operator is evaluated in scalar context (your second example), a boolean is indicating whether it matched or not is returned instead.

To answer your specific question, placing parens around $var forces it into list context and assigns the first element of the list returned from the pattern match to $var.

This is effectively the same as these statements:

my @matches = $my_string =~ /foo(.*)bar/;
my $var = $matches[0];

Upvotes: 2

Jim Garrison
Jim Garrison

Reputation: 86774

Because the regex match operator returns a list, and you must provide a list context if you want the list values. In the parentheses case you provide a list context, so the variable gets set... but only the first value returned would be saved. If your regex returned multiple sub-matches you'd need to provide more than one variable, as in:

($a,$b) = $string =~ /\s+(\S+)\s+(\S+)/;

In the bare (non-parentheses) case, you provide scalar context, and the match operator in scalar context returns a boolean indicating whether the pattern matched or not.

Upvotes: 1

Slaven Tomac
Slaven Tomac

Reputation: 1550

Because in first case you are doing regex matching in list context and http://perldoc.perl.org/perlrequick.html says in that case:

In list context, a match /regex/ with groupings will return the list of matched values ($1,$2,...)

In second case, regex return true (1)

Upvotes: 1

Related Questions