in reply to reference to an undefined key
You can't access attributes of an object before the object is created. It's like asking what the value of your bank account is, when you haven't even opened up an account yet.
You don't show where the $userId or $appName are coming from, but I suspect you'll be accepting them as params in your new() method.
What I would do here, is something like this, using an _init() method to do the lifting (untested). Note I've replaced $obj with $self, and extracted the variables for clarity, instead of just passing @_ around:
Update: The first half of my example doesn't perform properly. See AnomalousMonk's post below as to how it's broken. I've left it in as to not break context. Their reply has a fix.
use warnings; use strict; use Data::Dumper; package Test; sub new { my $self = bless {}, shift; my ($uid, $root, $app) = @_; my %attrs = $self->_init($uid, $root, $app); $self = \%attrs; return $self; } sub _init { my $self = shift; my ($uid, $root, $app) = @_; my %attrs; $attrs{Root} = $root; $attrs{UserDir} = $attrs{Root} . "Usr/$uid/"; $attrs{UserAppData} = $attrs{UserDir} . "$app", return %attrs; } package main; my $test = Test->new('steve', '/home/', 'perl'); print Dumper $test;
If you do want to do all the work in the constructor method, you can create the object up-front, then access all of its attributes before returning it:
sub new { my $obj = bless {}, shift; my ($uid, $root, $app) = @_; $obj->{Root} = $root; $obj->{UserDir} = $obj->{Root} . "Usr/$uid/"; $obj->{UserAppData} = $obj->{UserDir} . "$app", return $obj; }
-stevieb
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: reference to an undefined key
by AnomalousMonk (Archbishop) on Oct 10, 2015 at 15:39 UTC | |
by stevieb (Canon) on Oct 10, 2015 at 15:49 UTC | |
by exilepanda (Friar) on Oct 10, 2015 at 17:33 UTC | |
|
Re^2: reference to an undefined key
by exilepanda (Friar) on Oct 10, 2015 at 16:39 UTC | |
by AnomalousMonk (Archbishop) on Oct 10, 2015 at 17:33 UTC | |
by stevieb (Canon) on Oct 10, 2015 at 19:55 UTC |