http://www.perlmonks.org?node_id=899078


in reply to Compare field andsend mail

I would suggest calculating the time to be compared against once at the beginning of the script, and directly compare that with the date/time you extract from the file you are reading. The same type problem was discussed here.

One advantage you have in your file is that the format for the date/time sorts naturally because the most significant parts of the date begin at the left going to the right.

That is 'YYYY/MM/DD HH:MM:SS' is in a good order for sorts or comparisons.

#!/usr/dist/share/perl,v5.003/5bin.sun4/perl use strict; use warnings; use Time::Local qw/ timelocal_nocheck /;; use POSIX qw/ strftime /; my $secs = 3600; # 1 hour my ($s, $m, $h, $d, $mon, $y) = localtime; my $time_ago = strftime "%Y/%m/%d %H:%M:%S", localtime timelocal_nocheck $s - $secs, $m, $h, $d, $mon, $y; print "$time_ago was one hour ago\n"; my $mailprog = "|/usr/sbin/sendmail -t"; my $lst_email = 'someone@outthere.com'; # DATA should be saved as the spaecial filehandle # for self-contained programs (like this one) + #open (my $in, "/mylist.log") || die ("Can't Open data File: $!\n"); # while (<$in>) { while (<DATA>) { chomp; my ($datestamp, $status, $location) = split /\|/; if ($datestamp lt $time_ago && $status eq 'red') { # do email notification print "red for more than an hour\n$_\n"; } } __DATA__ 2011/04/12 12:50:24|red|florida 2011/04/12 15:20:21|green|tampa 2011/04/12 15:30:12|red|miami
Update: I hour ago could have been written:

my $hrs = 1;

and then subtracted from $h in the $time_ago formation.

my $time_ago = strftime "%Y/%m/%d %H:%M:%S", localtime timelocal_nocheck $s, $m, $h - $hrs, $d, $mon, $y;
To avoid possible errors in the time calculation, you could use a module made for dealing with dates, like DateTime.

use DateTime; my $date = DateTime->now->subtract(hours => 1); my $hr_before = $date->set_time_zone('local')->strftime("%Y/%m/%d %H:% +M:%S");