Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the parentheses so important when assigning this regex match?

Tags:

regex

perl

I have a piece of code:

$s = "<sekar kapoor>";
($name) = $s =~ /<([\S\s]*)>/;
print "$name\n";               # Output is 'sekar kapoor'

If the parentheses are removed in the second line of code like this, in the variable $name:

$name = $s =~ /<([\S\s]*)>/;   # $name is now '1'

I don't understand why it behaves like this. Can anyone please explain why it is so?

like image 814
Senthil kumar Avatar asked Feb 27 '23 07:02

Senthil kumar


1 Answers

In your first example you have a list context on the left-hand side (you used parentheses); in the second you have a scalar context - you just have a scalar variable.

See the Perl docs for quote-like ops, Matching in list context:

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.

like image 185
martin clayton Avatar answered Apr 08 '23 05:04

martin clayton