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
In reply to Re: reference to an undefined key
by stevieb
in thread reference to an undefined key
by exilepanda
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |