Category: Script Keywords: Time::Local
简单描述
近日闲来无事,写个小程序冶冶情。程序的用途是看看从我出生以来过了多长时间了?虽然我有年的概念可没有秒分时天的概念。
程序很简单,大部分脏累的工作都由Time::Local完成了。最核心的代码为:
my $in_time = timelocal($sec,$min,$hour,$day,$mon,$year);timelocal可以把我们所能看懂的年月日等换回1970年到现在的秒,它的功能与localtime正好反一下。
写的这么长就因为要写成Web格式。麻烦了点。
可以点击http://www.1313s.com/cgi-bin/App.cgi?q=time来看看你已经活了多少秒?
Code
#!/usr/bin/perl
use strict;
use warnings;
use CGI::Carp qw(fatalsToBrowser);
use CGI qw/:cgi/;
use Time::Local qw/timelocal/;
my $cgi = new CGI;
print $cgi->header(-charset=>'gb2312');
&interface unless ($cgi->param('year'));
my $sec = $cgi->param('sec');
my $min = $cgi->param('min');
my $hour = $cgi->param('hour');
my $day = $cgi->param('day');
my $mon = $cgi->param('mon');
my $year = $cgi->param('year');
$sec =~ /^[0-9]{1,2}$/ and $sec >= 0 and $sec < 60
or &interface("秒");
$min =~ /^[0-9]{1,2}$/ and $min >= 0 and $min < 60
or &interface("分");
$hour =~ /^[0-9]{1,2}$/ and $hour >= 0 and $hour < 24
or &interface("时");
$day =~ /^[0-9]{1,2}$/ and $day > 0 and $day < 32
or &interface("日");
$mon =~ /^[0-9]{1,2}$/ and $mon > 0 and $mon < 13
or &interface("月");
$year =~ /^[0-9]{4}$/ and $year > 1970
or &interface("年");
$mon--;
my $in_time = timelocal($sec,$min,$hour,$day,$mon,$year);
my $now = time;
&interface("年") if ($in_time > $now);
$sec = $now - $in_time;
$min = int($sec/60);
$hour = int($min/60);
$day = int($hour/24);
print "您总共过了 <b>$sec</b> 秒,<b>$min</b> 分, <b>$hour</b> 小时, <b>$day</b> 天<br>请珍惜时间!";
sub interface {
my $error = shift;
print qq~<h2><font color='red'>您所输入的$error有误,请查阅后再提交</font></h2>~ if ($error);
print <<HTML;
<form>
查看从你出生以来过了几秒几分几小时几天。<br>
请输入您的生日:<br>
<input type=text name=year size=4 value='$year'>年
<input type=text name=mon size=2 value='$mon'>月
<input type=text name=day size=2 value='$day'>日
<input type=text name=hour size=2 value='$hour'>时
<input type=text name=min size=2 value='$min'>分
<input type=text name=sec size=2 value='$sec'>秒<br>
<input type=submit></form>
HTML
exit;
}