0

In Perl regex, the documentation says

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

But how is it that when you provide an alternative option - when no match is found - TRUE or FALSE will be assigned even when in list context?

As an example, I want to assign the matched group to a variable and if not found, use the string value ALL.

my ($var) = $string =~ /myregex/ || 'ALL';

Is this possible? And what about multiple captured groups? E.g.

my ($var1, $var2) = $string =~ /(d.t)[^d]+(d.t)/ || 'dit', 'dat';

Where if the first group isn't matched, 'dit' is used, and if no match for the second is found 'dat'.

Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
  • Does it have to be a one liner? An `if` `else` and using `$1` and `$2` will probably be more readable – Recct Feb 25 '16 at 10:25
  • @Recct It doesn't have to be - as long as it's efficient. – Bram Vanroy Feb 25 '16 at 10:41
  • Also after the `||` those are in void context if everything on the left is false, even if you use the weaker `or` assumedly to be applied if the regex fails still nothing happens on the right. – Recct Feb 25 '16 at 10:41

1 Answers1

1

For the first requirement, you can use the ternary operator:

my $string = 'abded';
for my $f ('a' .. 'f') {
    my ($v1) = $string =~ /($f)/ ? ($1) : ('ALL') ;
    say "$f : $v1";
}

Output:

a : a
b : b
c : ALL
d : d
e : e
f : ALL
Toto
  • 89,455
  • 62
  • 89
  • 125