Search code examples
regexperlcapturing-group

Assign captured group to value, and if no match: assign string


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'.


Solution

  • 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