How do parentheses change the result of a regular expression?

Can anyone explain if the difference is between the two following syntaxes:

($x) = $a =~ /(\d+)/;

$y = $a =~ /(\d+)/;

In the example, if $a= 100lkj, then $x = 100, but $y = 1.

With this code, I am trying to extract the numerical value present in a string $a.

I do not understand why?

+4
source share
3 answers

When you write a variable inside a bracket, it invokes a list context. This means that the material you want to assign to this variable will also be interpreted as a list.

. - , . , . , 1 , , 1 .

.

$1, $2, $3,... ( ).

:

$a =~ /(\d+)/;
$x = $1;

BTW: $a $b sort. , :).

($x) = $a =~ /(\d+)/;
# $x is the first element of the RegEx return value
# ($x, $y, $z) = $a =~ /(\d)(\d)(\d)/;
# $x = first match, $y = second and so on.
+6

, , , . , "0" .

, , ; , , .

+4

=~ . $a abc123def456ghi, (123, 456). $x.

=~ , 1 .

To extract the values, do not use the return value of the regex operator, use variables $&and $1.. instead $9.

+1
source

Source: https://habr.com/ru/post/1524022/


All Articles