Determine the difference in match in the context of a list with capture and non-reactive regex?

According to perlretut

... in a scalar context, $time =~ /(\d\d):(\d\d):(\d\d)/ returns true or false. However, in the context of the list, it returns a list of matching values ($1,$2,$3) .

But I can not find an explanation of what is returned in the context of the list if the template matches, if there are no capture groups in regexp. Testing shows that this is list (1) (one element, integer 1). (Ancillary question - will it always be where it is defined?)

This makes it difficult to accomplish what I want:

 if (my @captures = ($input =~ $regexp)) { furtherProcessing(@captures); } 

I want furtherProcessing to furtherProcessing called if there is a match, with any captured groups being passed as arguments. The problem occurs when $regexp does not contain capture groups, because then I want furtherProcessing to furtherProcessing called without arguments, and not with a value of 1 , which happens in the above. I can not check (1) as a special case, for example,

 if (my @captures = ($input =~ $regexp)) { shift @captures if $captures[0] == 1; furtherProcessing(@captures); } 

since in the case

 $input = 'a value:1'; $regexp = qr/value:(\S+)/; 

@captures has a fixed value that looks the same as when using $regexp , but has no capture groups.

Is there a way to do what I want?

+6
source share
1 answer

You can use $#+ to find out how many groups were in the last successful match. If it is 0, then there were no groups, and you have (1) . (Yes, it will always be (1) if there are no groups, as described in perlop .)

So this will do what you want:

 if (my @captures = ($input =~ $regexp)) { @captures = () unless $#+; # Only want actual capture groups furtherProcessing(@captures); } 

Note that $#+ counts all groups, regardless of whether they match or not (as long as the entire RE matches). Thus, "hello" =~ /hello( world)?/ Will return 1 group, although the group does not match (the value in @captures will be undef ).

+8
source

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


All Articles