John said:
Kimi said:
I have a string "Tue Nov 7 14:04:16 2006: Unable to open prev pos
file" in a variable "myvariable" and I need to extract "Tue Nov 7
14:14:16 2006" to another variable..
I also would like to know if there are any way to compare the above
result with Current date and find the difference of days/months
$ perl -le'
use POSIX q/mktime/;
my $myvariable = "Tue Nov 7 14:04:16 2006: Unable to open prev pos file";
my $week_day = qr/Mon|Tue|Wed|Thu|Fri|Sat|Sun/;
my $mon_name = qr/Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec/;
my ( $mon, $day, $hour, $min, $sec, $year ) = $myvariable =~ /$week_day \s+
($mon_name) \s+ (\d+) \s+ (\d+) : (\d+) : (\d+) \s+ (\d+)/x;
print "$sec, $min, $hour, $day, $mon, $year";
my $old_date = mktime $sec, $min, $hour, $day, ( index( $mon_name, $mon ) -
index( $mon_name, q/Jan/ ) ) / 4, $year - 1900;
my $current_date = time;
my ( $diff_days, $diff_mons ) = ( gmtime $current_date - $old_date )[ 3, 4 ];
print for scalar localtime $old_date, scalar localtime $current_date, "Days:
$diff_days, Months: $diff_mons";
'
16, 04, 14, 7, Nov, 2006
Tue Nov 7 14:04:16 2006
Wed Nov 22 05:48:51 2006
Days: 15, Months: 0
Or, if you didn't feel like doing all that work yourself, take
advantage of modules on CPAN, like Date::Manip...
#!/usr/bin/perl
use strict;
use warnings;
use Date::Manip;
my $var = "Tue Nov 7 14:04:16 2006: Unable to open prev pos file";
my ($dttm) = ($var =~ /^(.*\d{4}):/);
my $date = ParseDate($dttm);
die "Couldn't parse date!\n" unless $date;
my $today = ParseDate("today");
my ($Y, $M, $W, $D, $h, $m, $s) =
(DateCalc($date, $today, \my $err, 1) =~ /\d+/g
);
print "Date was $Y year(s), $M month(s), $W week(s), $D day(s), $h
hour(s), $m minute(s) and $s second(s) ago\n";
__END__
Date was 0 year(s), 0 month(s), 2 week(s), 1 day(s), 0 hour(s), 47
minute(s) and 0 second(s) ago
Paul Lalli