This may be more of a programming concept question. I have been wondering about calling functions and returning values.
In my example, I have a package called Conn.pm that contains the code for connecting to a database. I can call this with:
# Get handle to the database.
my $dbh = getConn(); # Conn.pm is use'd
So here's the thing. In the package, $conn is declared and returned. This works. But I am puzzled how I can return a reference to $conn when $conn is declared inside the package function and should be destroyed after leaving the getConn() function?
In C++ programming, if I were to do something like that, then I would be returning a reference to a destroyed object unless I had created the object on the heap (using new). In this getConn() function, I don't see the "new" operator anywhere but yet I've seen the use of "new" in other perl packages.
Similarily, let's say I want to call a function called mkHeadersHash() (I just stuck this in the same Conn.pm package). I pass in an array and I get back out a reference to a hash with indexing.
my @ary = qw(red green blue);
my $hash = mkHeadersHash(@ary);
print "$_ : $hash->{$_}\n" for keys %$hash;
Again, the mkHeadersHash() function creates the %HeadersHash inside the function and returns a reference to it. But the %HeadersHash hash was not destroyed after leaving that function (because my return value pointed to valid data). I would have expected my hash reference to be pointing to nothing.
So in terms of this specific question, how is this $conn and %HeadersHash able to hang around? In terms of programming concepts and practices, what is the appropriate way to deal with calling functions and returning values using a standard practice similar to many other languages? Is it better to declare $conn or $hash in the main program and pass these as references to the functions in the package? I'm sure there are many ways to do this so I'm interested in best practices.
This is a 300 point question because I am hoping to receive multiple, valuable answers.