CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Instance variable issue

 



spire01
New User

Aug 22, 2011, 10:12 AM

Post #1 of 5 (1422 views)
Instance variable issue Can't Post

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

Post #2 of 5 (1419 views)
Re: [spire01] Instance variable issue [In reply to] Can't Post

$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

Post #3 of 5 (1416 views)
Re: [BillKSmith] Instance variable issue [In reply to] Can't Post

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

Post #4 of 5 (1414 views)
Re: [spire01] Instance variable issue [In reply to] Can't Post

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


spire01
New User

Aug 22, 2011, 5:41 PM

Post #5 of 5 (1410 views)
Re: [BillKSmith] Instance variable issue [In reply to] Can't Post

Great, thank you!

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives