http://www.perlmonks.org?node_id=1144375


in reply to Re: reference to an undefined key
in thread reference to an undefined key

    sub new {
        my $self = bless {}, shift;
        ...
        my %attrs = $self->_init($uid, $root, $app);
        $self = \%attrs;
        return $self;
    }

    sub _init {
        ...
        my %attrs;
        ...
        return %attrs;
    }

Unfortunately, overwriting the blessed reference to an anonymous hash  $self with an unblessed reference to the  %attrs hash destroys the blessing an object reference needs. Your original code produces

$VAR1 = { 'Root' => '/home/', 'UserDir' => '/home/Usr/steve/', 'UserAppData' => '/home/Usr/steve/perl' };
from the  print Dumper $test; statement. (Update: The second definition of  new() returns a properly blessed object.)

A minimal change to produce a properly blessed object reference might be something like

c:\@Work\Perl>perl -e "use warnings; use strict; ;; use Data::Dumper; ;; package Test; ;; sub new { my $self = bless {}, shift; my ($uid, $root, $app) = @_; ;; return $self->_init($uid, $root, $app); ;; } ;; sub _init { my $self = shift; my ($uid, $root, $app) = @_; ;; $self->{Root} = $root; $self->{UserDir} = $self->{Root} . qq{Usr/$uid/}; $self->{UserAppData} = $self->{UserDir} . $app, ;; return $self; } ;; package main; ;; my $test = Test->new('steve', '/home/', 'perl'); print Dumper $test; " $VAR1 = bless( { 'Root' => '/home/', 'UserDir' => '/home/Usr/steve/', 'UserAppData' => '/home/Usr/steve/perl' }, 'Test' );
(However, I find the whole  my $obj = bless { What => 'ever' }, shift; syntax a bit funky if the original goal is "to state the logic of the properties in clear." But that's another story...)


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^3: reference to an undefined key
by stevieb (Canon) on Oct 10, 2015 at 15:49 UTC

    Nice catch, that's a big one I'm surprised I completely overlooked. Thanks :)

Re^3: reference to an undefined key
by exilepanda (Friar) on Oct 10, 2015 at 17:33 UTC
    Thanks for your reply and this reminded me something, do you have any feed back for my updates in the post ?