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


Correct Option: D

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.

Find more quizzes: