Reputation: 739
I have written a perl script, where I call a subroutine to insert the fields into a database table. The subroutine is called in another file Test.pm other than the main perl file Test.pl. In Test.pm I have the following fields to insert into table
my $date = localtime->strftime('%Y-%m-%d %H:%M:%S');
my $time = localtime->strftime('%H:%M:%S');
But, here I get the following error
Can't locate object method "strftime" via package
What is this error and why does this occur. If I pass the parameters of $date
and $time
from Test.pl
, the script works fine , how can I solve this?
Below is the subroutine :
sub send_message
{
my $date = localtime->strftime('%Y-%m-%d %H:%M:%S');
my $time = localtime->strftime('%H:%M:%S');
print "Date : $date Time : $time";
my $sql1 = "Insert into testtable(time,date) values('$time','$date')";
my $sth1 = $dbh->prepare($sql1);
$sth1->execute
or die "SQL Error: $DBI::errstr\n";
return;
}
Upvotes: 2
Views: 5352
Reputation: 2391
First: the error means that your script wants to call the method strftime
which shall be defined in a special package.
Looking at your script, the following happens:
localtime
which is a method and returns the current time as a string, e.g. "Thu Jun 20 01:14:01 2013"
strftime
defined in a package (module) with the name returned by localtime
. That doesn't work.strftime
is defined in POSIX
and takes >1 parameters: the format and the time.
You probably want to call:
use POSIX;
my $date = POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime);
my $time = POSIX::strftime('%H:%M:%S', localtime);
or, because you're calling this method twice:
use POSIX;
my @localtime = localtime;
my $date = POSIX::strftime('%Y-%m-%d %H:%M:%S', @localtime);
my $time = POSIX::strftime('%H:%M:%S', @localtime);
since localtime
returns an array which should be the input to strftime.
Upvotes: 9
Reputation: 22952
Close @Jim Garrison, but I think it's a missing use Time::Piece issue.
@Rudra - try adding that to the top of your script and see if it does the job.
Upvotes: 6
Reputation: 86774
localtime
is a builtin function and strftime
is part of the POSIX
package, so you don't use ->
syntax. The best reference is at perldoc. For example
use POSIX qw(strftime);
$now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;
# or for GMT formatted appropriately for your locale:
$now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime;
Upvotes: 0