James Bond
James Bond

Reputation: 3007

PM module in Perl Program Error :: Can't call method "prepare" on an undefined value at

I must ascertain how to eliminate the error.

$ perl use_pkg.pl
    
Can't call method "prepare" on an undefined value at use_pkg.pl line...

I have two files via.

First is a perl package PKG.pm

package PKG;
require 5.000;
require Exporter;
@ISA = qw(Exporter);
 
@EXPORT = qw(SoxDBLogin);  
use DBI;

sub SoxDBLogin
{
    # these values are provided using Unix env variables
    $user     = $user|| $ENV{"DBUSER"}; 
    $pswd     = $pswd||$ENV{"DBPSWD"}; 
    $srvr     = $srvr||$ENV{"DBSRVR"}; 
    $dbName   = $dbName|| $ENV{"DBNAME"};

    printf STDOUT ("Program %s: DBUSER <%s>,  DBSRVR <%s>, DBNAME <%s>\n",$0,$user,$srvr,$dbName);
    $DSN = "driver={ODBC Driver 17 for SQL Server};server=$srvr;data base=$dbName;uid=$user;pwd=$pswd";
    $dbh = DBI->connect("DBI:ODBC:$DSN") or die "Couldn't open database : $DBI::errstr\n";
}

Another file has a perl program use_pkg.pl

#!/usr/bin/perl

use PKG;
use DBI;

&main;

sub main
{
    &initialize;
    &delFeedForDay;
}


sub initialize
{
    # these values are provided using Unix env variables
    $user = $ENV{"DBUSER"};
    $pswd = $ENV{"DBPSWD"};
    $srvr = $ENV{"DBSRVR"};
    $dbName = $ENV{"DBNAME"};

    &SoxDBLogin($user,$pswd,$srvr,$dbName);
}

sub delFeedForDay
{
    
    my $sql = "SELECT count(*) FROM [myDb].[dbo].[adp_users]" ;

    # I receive the error "Can't call method "prepare" on an undefined value at" on next line     
    my $sth = $dbh->prepare($sql) or die "Can't prepare statement: $DBI::errstr";
    my $exStat = $sth->execute() or die "ERROR while query execution...exiting $DBI::errstr\n";
    
    my $data = $sth->fetchrow();
    printf STDOUT ("Data : $data \n");
    
    $sth->finish();
}

Upvotes: 1

Views: 181

Answers (1)

James Bond
James Bond

Reputation: 3007

Used return for getting the DB handle from the sub SoxDBLogin

return $dbh ;

Then simply assigned it to a variable in sub initialize

$dbh = &SoxDBLogin($user,$pswd,$srvr,$dbName); 

It worked perfectly.

Upvotes: 1

Related Questions