Home: Perl Programming Help: Intermediate:
Instance variable issue



spire01
New User

Aug 22, 2011, 10:12 AM


Views: 1892
Instance variable issue

Hi,

I'm having a problem trying to access an instance variable in a singleton class I'm building. Here's a rough draft of what I've got:

package customDB;

my ($db) = 0;

sub instance
{
unless ($db)
{
my ($class);
$class = shift;

$db = {};

bless $db, $class;
}

return $db;
}


sub function1
{
my ($db, $name) = @_;

return $db{$name} if exists $db{$name}; #THIS LINE

return undef;

}
1;

The error when I try to compile:
Global symbol "%db" requires explicit package name at ...
Global symbol "%db" requires explicit package name at ...

Any thoughts?


BillKSmith
Veteran

Aug 22, 2011, 11:47 AM


Views: 1889
Re: [spire01] Instance variable issue

$db is a reference to a hash, not a hash. You must dereference $db to use the hash.


Code
return $db->{$name} if exists $db->{$name}; #THIS LINE  

Good Luck,
Bill


spire01
New User

Aug 22, 2011, 1:08 PM


Views: 1886
Re: [BillKSmith] Instance variable issue

Thank you!

One more question - I've been dereferencing like this:

my %temp = %$db;

$temp{$name} = $x;

But conceptually, I'd like to do this:

%$db{$name} = $x;

Is there anyway to do this syntactically?

Thanks!


BillKSmith
Veteran

Aug 22, 2011, 3:00 PM


Views: 1884
Re: [spire01] Instance variable issue

See Syntax->Using References->Using Rule 1 in perldoc perlreftut.
Good Luck,
Bill


spire01
New User

Aug 22, 2011, 5:41 PM


Views: 1880
Re: [BillKSmith] Instance variable issue

Great, thank you!