clock scan, the perl way
Recently I was helping someone to find out those directories (in yyyymmdd- naming convention) that is 2 weeks old. It can be easily done in Tcl with clock scan. However, not every operating system comes with Tcl. As far as I know Tclsh8.3 is only available in Solaris 9 onwards, but not in Solaris 8.
If I were to do it in shell script, it will be very tough. In this case, I chose the Perl way for my implementation because Perl is available since Solaris 8.
$ cat clockscan.pl
#! /usr/bin/perl
$narg=$#ARGV+1;
if ( $narg < 2 || $narg > 3 ) {
die "Usage: $0 [ago]\n";
}
$num=$ARGV[0];
# unit
$_=lc($ARGV[1]);
if ( /^second[s]?$/ ) {
$factor=1;
} elsif ( /^minute[s]?$/ ) {
$factor=60;
} elsif ( /^hour[s]?$/ ) {
$factor=60*60;
} elsif ( /^day[s]?$/ ) {
$factor=24*60*60;
} elsif ( /^week[s]?$/ ) {
$factor=7*24*60*60;
} elsif ( /^month[s]?$/ ) {
$factor=30*24*60*60;
} elsif ( /^year[s]?$/ ) {
$factor=365*24*60*60;
} else {
die "Error $unit unknown";
}
# ago
$_=lc($ARGV[2]);
$sign=1;
if ( /^ago$/ ) {
$sign=-1;
}
# count
$diff=$sign*$factor*$ARGV[0];
$,=" ";
$now=time();
($sec,$min,$hr,$day,$mth,$year)=localtime($now+$diff);
printf("%04d-%02d-%02d %02d:%02d:%02d\n",$year+1900,$mth+1,$day,$hr,$min,$sec);
$ ./clockscan.pl 2 weeks ago
2007-04-03 18:04:07
$ ./clockscan.pl -2 weeks
2007-04-03 18:04:12
$ ./clockscan.pl 1 year ago
2006-04-17 18:04:17
$ ./clockscan.pl 2 months
2007-06-16 18:04:22
Labels: Perl, shell script, Solaris, Tcl


0 Comments:
Post a Comment
<< Home