Multiple choice technology programming languages

What gets printed? package A; sub new { my \$class = shift; my \$self = {}; \$self->init(); return bless \$self, \$class; }; sub init { my \$self = shift; \$self->{key} = 'value'; } sub get { my (\$self, \$key) = @_; return \$self->{\$key}; } package main; my \$obj = A->new(); print \$obj->get('key'), "\n";

  1. empty string

  2. value

  3. the code will fail

  4. None of the above

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

The code fails because init() is called before bless() returns a fully constructed object. When init() attempts $self->{key} = 'value', $self is still an unblessed hash reference (not yet an object of class A), but more critically, calling init() inside new() before the bless completes means $self lacks proper object context. Perl's bless() operation must complete before the object can properly call its own methods. The correct pattern is to bless first, then initialize, or use a post-bless initialization hook.

AI explanation

This code fails at runtime, not because of 'get' (which is defined and would correctly return $self->{key}), but because of the bug inside 'new': it calls $self->init() before \$self has been blessed into class A. At that point \$self is still a plain, unblessed hash reference, and Perl does not allow method-call syntax ('->') on an unblessed reference — it throws a runtime error like "Can't call method "init" on unblessed reference". Bless must happen first, then methods can be invoked. So neither 'value' nor an empty string is printed; the program dies before reaching the print statement, matching 'the code will fail'.