in reply to Includes, strict and pointers.

I have no idea where you got the idea that you needed pointers, but if this is common code, you might want to create a library/module and put the code in there.

For example:

package Mylibrary; use strict; use DBI; my $database="somedb:localhost"; my $username="username"; my $password="password"; sub connect { my $dbh = DBI->connect("DBI:mysql:$database", "$username","$password") or error_fatal("blah"); return $dbh; } sub get_current_vote { my ($dbh) = @_; # if we're not connected (or weren't passed # a connection), connect $dbh ||= connect(); my $sth = $dbh->prepare("SELECT current_vote FROM vote_count;"); $sth->execute() or die $dbh->errstr(); my $current_vote = ($sth->fetchrow_array())[0]; return $current_vote; } 1;
and then you can do the following in your scripts:
# my funky script use strict; use DBI; use Mylibrary; # connect to library: my $dbh = Mylibrary::connect(); # get current vote: my $current_vote = Mylibrary::get_current_vote($dbh);

No need for pointers, and the yucky require can be omitted too. What is more, you've got a ready location for any extra functions you find yourself using in all, or most of your scripts. (You can also export your functions from the Mylibrary namespace, but you can read up on that.)

Hope it helps,
jarich.

Update: Call the file with the Mylibrary package in it Mylibrary.pm, and either store it in the same directory with all the scripts that use it or add a use lib line in your scripts like the following:

# my funky script use strict; use DBI; use lib '/path/to/my/library/'; use Mylibrary;
Note that the use lib line must be before the use Mylibrary line.

Replies are listed 'Best First'.
Re: Re: Includes, strict and pointers.
by joe++ (Friar) on Sep 23, 2002 at 09:04 UTC
    Hi,

    To add my $0.02... if you're going the OO way, you can add a DESTROY {} routine which checks for open DB connections and properly closes them before going out of scope. This is especially useful when using commit/rollback (you should do a rollback in this case of course!).

    sub DESTROY { $self = shift; # assume database handle is stored in blessed object if ($self->{dbh}) $self->{dbh}->rollback(); $self->{dbh}->disconnect() || croak $self->{dbh}->errstr; } }

    I like this "trick" very much, because it saves me if some unforeseen error occurs and of course it serves the virtue of laziness.

    --
    Cheers, Joe

Re: Re: Includes, strict and pointers.
by lagrenouille (Acolyte) on Sep 23, 2002 at 06:36 UTC
    Cheers

    That makes a lot of sense, I'll go with that...

    One question though... the "use Mylibrary" will use a file I assume, called Mylibrary.pm ..?
    If so, where does this file need to be located ?
    or can I specify it with a path prepended to the package name?

    Cheers
    lagrenouille