title: Is there a way to localise a package in Perl - database handle issues?
body: <p>I need to instantiate a new $dbh using DBI.</p>
  
  <p>My objects usually have a $dbh present when they're created.</p>
  
  <p>When I try to create a new $dbh using</p>
  
  <pre><code>my $dbh = MyLib::Connect();
  </code></pre>
  
  <p>and after performing some DB operations doing</p>
  
  <pre><code>$dbh-&gt;disconnect();
  </code></pre>
  
  <p>my downstream code's $dbh is closed. Is there a way to get what I'm after? I've seen some example code that does two DBI->connect(...) calls but using the same code as an example produces the same result - it's like MyLib is caching the returned $dbh value.</p>
  
  <p>Example code:</p>
  
  <pre><code>package MyLib;
  sub DoConnect { 
    ...
    my $dbh = DBI-&gt;connect(...);
    return($dbh)
  }
  
  package Object;
  sub GetData {
    my ($id) = @_;
    my $dbh = MyLib::DoConnect(); # This should be separate
    ...
    $dbh-&gt;commit()
    $dbh-&gt;disconnect();
    return($someData);
  }
  
  package AnotherObject;
  sub DoSomething {
    my ($self) = @_; 
    # $self had a dbh set on instantiation with MyLib::DoConnect();
    my $newData = Object::GetData($self-&gt;id);
    my $moreData = GetDataUsingDBH($self-&gt;dbh); # the dbh is closed!!!
  }
  </code></pre>
  
  <p>Is what I need to do possible without starting a separate thread (which I can't guarantee will finish before GetDataUsingDBH is called). Should I do a system call to an external program to wait for it to finish? Does my question even make sense?</p>