Multiple choice technology programming languages

What will be the value of $val? my $str = 'aa bb cccc'; my $val = () = $str =~ /\w+/g;

  1. undef

  2. aa

  3. cccc

  4. 3

  5. 0

Reveal answer Fill a bubble to check yourself
D Correct answer
Explanation

The assignment of the global regex match to an empty list () = ... forces list context, returning all matches. Assigning this expression to the scalar $val evaluates the list in scalar context, yielding the count of matches, which is 3.

AI explanation

To determine the value of \$val, let's break down the code step by step:

my \$str = 'aa bb cccc';
my $val = () = $str =~ /\w+/g;

In the second line, the regular expression /\w+/g is used to match one or more word characters in the string \$str. The g modifier indicates that the regular expression should be executed globally, meaning it will match all occurrences in the string.

The \$str =~ /\w+/g expression returns a list of all the matches found in the string. In this case, the matches are 'aa', 'bb', and 'cccc'.

The () surrounding the assignment operator = in the line $val = () = $str =~ /\w+/g is known as the list context. It forces the right-hand side of the assignment to be evaluated in a list context.

The () = $str =~ /\w+/g expression assigns the matches to an empty list (). However, the assignment is happening in a scalar context, so the empty list is being evaluated as the number of elements in the list.

Therefore, the value of $val will be the number of matches found, which is 3.

The correct answer is D) 3.