我想创建一个脚本,它将接收2个参数(小时和分钟)(HH1:MN1和HH2:MN2)
我从这开始,但不知道如何继续 我们欢迎任何帮助或想法进行计算 感谢
#!/usr/bin/perl
if ($#ARGV != 2)
{
print STDERR "Erreur Parameters have to be 2\n";
exit (-1);
}
if ($ARGV[0] = ~ / ([0-9] | 1 [0-9] ? [0-9] | 200 ) : ( [0-5] ? [0-9] ) /)
{
$heures1 = $1;
$minutes1 = $2;
}
else
{
print STDERR "first parameter invalid\";
exit (-1);
}
if ($ARGV[1] = ~ / ([0-9] | 1 [0-9] ? [0-9] | 200 ) : ( [0-5] ? [0-9] ) /)
{
$heures2 = $3;
$minutes2 = $4;
}
`else `
{
print STDERR "Second parameter invalid\";
exit (-1);
$heures = $heures1 + $heures2;
$minutes = $minutes1 + $minutes2'
答案 0 :(得分:2)
验证码非常简单:
sub usage {
print STDERR $_[0] if @_;
print STDERR "usage: ...\n";
exit(1);
}
usage() if @ARGV != 2;
my ($hours1, $minutes1) = $ARGV[1] =~ /^([0-9]+):([0-9]+)\z/ or usage();
my ($hours2, $minutes2) = $ARGV[1] =~ /^([0-9]+):([0-9]+)\z/ or usage();
0 <= $hours1 && $hours1 <= 200 or usage("Invalid number of hours for first argument\n");
0 <= $minutes1 && $minutes1 <= 59 or usage("Invalid number of minutes for first argument\n");
0 <= $hours2 && $hours2 <= 200 or usage("Invalid number of hours for second argument\n");
0 <= $minutes2 && $minutes2 <= 59 or usage("Invalid number of minutes for second argument\n");
范围检查可以通过正则表达式完成,但它容易出错并且不可读。
/^0*(0|1[0-9]{0,2}|2(?:00?|[1-9])?|[3-9][0-9]?):0*(0|[1-5][0-9]?|[6-9])\z/
(正则表达式可能有点简单,但它的编写实际上消除了回溯的可能性。)
你已经asked我们优雅地为数学部分提供了解决方案,那你为什么要再问一次呢?
my ($hours1, $minutes1) = split /:/, $arg1;
my ($hours2, $minutes2) = split /:/, $arg2;
my $hours = $hours1 + $hours2;
my $minutes = $minutes1 + $minutes2;
$hours += ($minutes - ($minutes % 60)) / 60; $minutes %= 60;
my $days = ($hours - ($hours % 24)) / 24; $hours %= 24;
my $weeks = ($days - ($days % 7)) / 7; $days %= 7;
对于输出部分,您应该能够自己管理。一个有用的提示:
sprintf('%02d', $minutes) # 0-padded to two digits
答案 1 :(得分:0)
#!/usr/bin/perl
die "Erreur Parameters have to be 2" if (scalar(@ARGV) != 2)
if ($ARGV[0] =~ /^([0-9]|1[0-9]?[0-9]|200):([0-5]?[0-9])$/) {
$heures1 = $1;
$minutes1 = $2;
} else {
die "first parameter invalid";
}
if ($ARGV[1] =~ /^([0-9]|1[0-9]?[0-9]|200):([0-5]?[0-9])$/) {
$heures2 = $3;
$minutes2 = $4;
} else {
die "Second parameter invalid";
}
$heures = $heures1 + $heures2;
$minutes = $minutes1 + $minutes2'