in reply to Re: OO question
in thread OO question

Your $DBH variable is a lexical in the scope of the file that your package is in. It starts out as undef, but when you set it, it will stay set. It never goes out of scope and so never loses its value.

I know that $DBH is file lexical and visiable to the MyDB package. but i think the second call to MyDB->dbh is independent to the first one and like a new instance of something.

Replies are listed 'Best First'.
Re^3: OO question
by ikegami (Patriarch) on Mar 18, 2007 at 02:11 UTC

    but i think the second call to MyDB->dbh is independent to the first one and like a new instance of something.

    New instance of what? $DBH? no.

    { package Cow; my $i; sub moo { print(("moo " x ++$i), "\n"); } } Cow->moo(); # moo Cow->moo(); # moo moo Cow->moo(); # moo moo moo
    { package MyDB; my $DBH; sub dbh { if ($DBH) { print "found existing $DBH\n"; } else { $DBH = 'dbh'; print "Init $DBH\n"; } } } MyDB->dbh(); # Init dbh MyDB->dbh(); # Found existing dbh MyDB->dbh(); # Found existing dbh