How to Print Spelled out month names rather than numbers

青春壹個敷衍的年華 提交于 2019-12-24 17:57:38

问题


How can you get Perl to print names of months rather than their numbers for example: 9 should appear as September. I would like the program below to print names of months rather than their numbers.

#!/usr/bin/perl

use strict;
use warnings;
use Date::Easter;

print "Please enter a year";
chomp (my $year = <STDIN>);

my ($m1, $d1) = easter ($year);
my ($m2, $d2) = julian_easter ($year);
my ($m3, $d3) = orthodox_easter ($year);

print "Gregorian => Month: $m1 Day: $d1\n";
print "Julian    => Month: $m2 Day: $d2\n";
print "Orthodox  => Month: $m3 Day: $d3\n";

回答1:


I'm too lazy to download this module to see if months are from 0 to 11 or 1 to 12. For this, I'm assuming months are from 0 to 11.

Easiest way is to create an array with the month names:

my @month_list = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);

my ($m1, $d1) = easter ($year);
my ($m2, $d2) = julian_easter ($year);
my ($m3, $d3) = orthodox_easter ($year);

print "Gregorian => Month: $month_list[$m1] Day: $d1\n";
print "Julian    => Month: $month_list[$m2] Day: $d2\n";
print "Orthodox  => Month: $month_list[$m3] Day: $d3\n";

If months are numbered from 1 to 12, add a fake month to the beginning of the array:

my @month_list = qw(Foo Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);



回答2:


I'm using buil-in POSIX module:

#!/usr/bin/perl

use strict;
use warnings;
use Date::Easter;
use POSIX qw(strftime);

my %dispach_sub = (
    easter          => \&easter,
    julian_easter   => \&julian_easter,
    orthodox_easter => \&orthodox_easter,
);

print "Please enter a year: ";
chomp( my $year = <STDIN> );

foreach my $key ( keys %dispach_sub ) {

    print "[$key]\t";
    my ( $month, $day ) = $dispach_sub{$key}->($year);
    print POSIX::strftime( "Month: %B Day: %d",
        0, 0, 0, $day, $month - 1, $year - 1900 ),
      "\n";
}


来源:https://stackoverflow.com/questions/15800862/how-to-print-spelled-out-month-names-rather-than-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!