سؤال

Im trying to use strftime on a data string :

my $date = '2013-10-31 13:55';
my $new_date = $date->strftime('%Y-%m-%d %H:%M:%S');

But i always get the error

 "Can't call method "strftime" without a package or object reference"

Please suggest what i can do about this

هل كانت مفيدة؟

المحلول

As others have pointed out, you are are possibly overcomplicating this by trying to use strftime() here. You also have a misunderstanding where you are trying to call a method on a variable that doesn't contain an object.

I think that perhaps you were trying to write something like this.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;
use Time::Piece;

# The original date as a string
my $date_str = '2013-10-31 13:55';
# Parse the date string and create a Time::Piece object
my $date     = Time::Piece->strptime($date_str, '%Y-%m-%d %H:%M');
# Create a new (improved!) date string using strftime()
my $new_date = $date->strftime('%Y-%m-%d %H:%M:%S');
say $new_date;

Time::Piece has been a standard Perl library for several years.

نصائح أخرى

To convert a date from one format to another, one normally parses the original representation into its parts, then formats them into the desired representation. However, all that's missing in this case is the seconds, so all you need is the following:

 my $new_date = $date . ':00';

In your example, $date is a scalar, not an object. It does not have a method strftime (hence the error saying there is no package or object reference). As ikegami said, if all you're trying to do is add seconds to your string, append them with the . operator. Don't use a sledgehammer to crack a nut.

If you're doing something less trivial to the format, you can do something like this with DateTime and DateTime::Format::Strptime:

    use DateTime;
    use DateTime::Format::Strptime;

    my $date = '2013-10-31 13:55';
    my $parser = DateTime::Format::Strptime->new(pattern => '%Y-%m-%d %H:%M');

    # Parse string into a DateTime object
    my $dt = $parser->parse_datetime($date);

    # Print DateTime object with a custom format
    print $dt->strftime('%a, %d %b %Y %H:%M:%S %z');
    # Thu, 31 Oct 2013 13:55:00 +0000
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top