Multiple choice technology programming languages

What will be the value of $keys? my %hash; $hash{undef} = undef; $hash{''} = ''; my $keys = keys(%hash);

  1. undef

  2. 0

  3. 1

  4. 2

  5. the code is ill-formed

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

In Perl hashes, undef (as a key) and empty string '' are different keys. When both are set as keys with undef values, the hash has 2 distinct key-value pairs. The keys() function in scalar context returns the count of keys, which is 2. This tests understanding that undef and '' are distinct values as hash keys.

AI explanation

The value is 2, so the marked answer (id 567518) is CORRECT. The flag's premise is wrong. In Perl, a bareword used as the sole content of a hash subscript is AUTO-QUOTED. So $hash{undef} does NOT call the undef() function — it uses the literal string 'undef' as the key. Thus the two assignments create two distinct keys: 'undef' and '' (empty string). keys(%hash) returns 2. I verified this by running Perl: the code as written yields keys=2 with keys ['undef'] and ['']. Only if you force evaluation with $hash{undef()} does undef get called, stringify to '', collide with $hash{''}, and give keys=1. Since the code uses the bareword undef (auto-quoted), the answer is 2.