#!/usr/bin/perl
@month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
@week = ("Sunday", "Monday","Tuesday", "Wednesday","Thursday", "Friday",
"Saturday");
print "date:\n";
$date=<STDIN>;
print "mon:\n";
$mon=<STDIN>;
print "year:\n";
$year=<STDIN>;
if ( ($year % 400 == 0) || ($year % 4 == 0) && ($year % 100 != 0) )
{
$month[1] = 29 ;
for($i = 0 ; $i < $mon - 1 ; $i++)
{
$s = $s + $month[$i] ;
$s = $s + ($date + $year + ($year / 4) - 2) ;
$s = $s % 7 ;
}
}
print $week[$s+1] ;
我已经尝试学习perl几天了,我写了这段代码来查找给定日期的一天。实际上我是从C代码转换而来的。但是它不起作用。输出始终是星期一。我在哪里犯错?
最佳答案
不要自己做。使用模块。十年来,Time::Piece一直是Perl发行版的标准组成部分。
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use Time::Piece;
print "date:\n";
chomp(my $date = <STDIN>);
print "mon:\n";
chomp(my $mon = <STDIN>);
print "year:\n";
chomp(my $year = <STDIN>);
my $tp = Time::Piece->strptime("$year-$mon-$date", '%Y-%m-%d');
say $tp->fullday;
我进行了其他一些调整:
use strict
和use warnings
my
声明变量chomp()
从输入更新:我现在更详细地查看了您的代码。那里只有一个错误。
您的逻辑如下所示:
if (we're in a leap year) {
Change the @months array to deal with leap years
Do the maths to calculate the day
}
当它应该看起来像这样时:
if (we're in a leap year) {
Change the @months array to deal with leap years
}
Do the maths to calculate the day
因此,除非您输入的年份是a年,否则您将跳过所有计算。这意味着从未给$ s赋值。 Perl将未定义的值视为0,因此您的最终声明始终在打印周一的
$week[0 + 1]
。如果诸如Time::Piece之类的模块不可用,则Perl程序员将这样编写代码:
#!/usr/bin/perl
# Force us to declare variables.
use strict;
# Get Perl to tell us when we're doing something stupid
use warnings;
# Allow the use of say()
use feature 'say';
# Declare variables with my()
my @month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
# qw(...) defines a list without all that tedious punctuation
my @week = qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday);
print "date:\n";
# Use chomp() to remove newlines from input
chomp(my $date = <STDIN>);
print "mon:\n";
chomp(my $mon = <STDIN>);
print "year:\n";
chomp(my $year = <STDIN>);
# This logic can be cleaned up a lot.
if ( ($year % 400 == 0) || ($year % 4 == 0) && ($year % 100 != 0) ) {
$month[1] = 29 ;
}
# Initialise $s to avoid warnings later
my $s = 0;
# A foreach look is almost always cleaner than for (;;)
foreach my $i (0 .. $mon - 2) {
# Haven't checked your calculations (but they seem to work
# += is useful shortcut
$s += $month[$i];
$s += ($date + $year + ($year / 4) - 2);
$s %= 7;
}
# say() is like print() but with an extra newline
say $week[$s+1];
关于perl - 从给定日期查找日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45573680/