Time in Perl
use strict;
use warnings;
use Time::Piece;
use Time::Seconds;
# We'll start by getting the current time.
my $now = localtime;
print $now, "\n";
# You can build a time struct by providing the
# year, month, day, etc. Times are always associated
# with a Location, i.e. time zone.
my $then = Time::Piece->strptime("2009-11-17 20:34:58", "%Y-%m-%d %H:%M:%S")->add_nanoseconds(651387237);
$then = $then->gmtime; # Convert to UTC
print $then, "\n";
# You can extract the various components of the time
# value as expected.
print $then->year, "\n";
print $then->mon, "\n";
print $then->mday, "\n";
print $then->hour, "\n";
print $then->min, "\n";
print $then->sec, "\n";
print $then->nanosecond, "\n";
print $then->time_zone, "\n";
# The Monday-Sunday Weekday is also available.
print $then->day, "\n";
# These methods compare two times, testing if the
# first occurs before, after, or at the same time
# as the second, respectively.
print $then < $now ? "true\n" : "false\n";
print $then > $now ? "true\n" : "false\n";
print $then == $now ? "true\n" : "false\n";
# The subtraction returns a Time::Seconds object representing
# the interval between two times.
my $diff = $now - $then;
print $diff, "\n";
# We can compute the length of the duration in
# various units.
print $diff->hours, "\n";
print $diff->minutes, "\n";
print $diff->seconds, "\n";
print $diff->nanoseconds, "\n";
# You can use addition to advance a time by a given
# duration, or subtraction to move backwards by a duration.
print $then + $diff, "\n";
print $then - $diff, "\n";This Perl script demonstrates various operations with dates and times, similar to the original example. Here’s a breakdown of the changes and explanations:
We use the
Time::PieceandTime::Secondsmodules, which provide object-oriented interfaces for date and time manipulation in Perl.The
localtimefunction fromTime::Pieceis used to get the current time.To create a specific time, we use
Time::Piece->strptimeto parse a string, then add nanoseconds separately.Time component extraction is done using methods of the
Time::Pieceobject.Time comparisons are done using Perl’s comparison operators.
Time difference is calculated by subtracting two
Time::Pieceobjects, which returns aTime::Secondsobject.Duration components are accessed using methods of the
Time::Secondsobject.Time addition and subtraction are performed using the
+and-operators.
Note that Perl’s time handling might not be as precise as Go’s, especially when it comes to nanoseconds. The exact behavior may depend on the system and Perl version.
To run this script, save it as time_example.pl and execute it with:
$ perl time_example.plThe output will be similar to the original example, showing various time and duration operations.