0

我有这个代码>

if ($firstDayOfTheMonth == "Monday")
{

    $eachDay["monday1"]="1st";
    $eachDay["tuesday1"]="2nd";
    $eachDay["wednesday1"]="3rd";
    $eachDay["thursday1"]="4th";
    $eachDay["friday1"]="5th";
    $eachDay["saturday1"]="6th";
    $eachDay["sunday1"]="7th";
    $eachDay["monday2"]="8th";
    $eachDay["tuesday2"]="9th";
    $eachDay["wednesday2"]="10th";
    $eachDay["thursday2"]="11th";
    $eachDay["friday2"]="12th";
    $eachDay["saturday2"]="13th";
    $eachDay["sunday2"]="14th";
    $eachDay["monday3"]="15th";
    $eachDay["tuesday3"]="16th";
    $eachDay["wednesday3"]="17th";
    $eachDay["thursday3"]="18th";
    $eachDay["friday3"]="19th";
    $eachDay["saturday3"]="20th";
    $eachDay["sunday3"]="21st";
    $eachDay["monday4"]="22nd";
    $eachDay["tuesday4"]="23rd";
    $eachDay["wednesday4"]="24th";
    $eachDay["thursday4"]="25th";
    $eachDay["friday4"]="26th";
    $eachDay["saturday4"]="27th";
    $eachDay["sunday4"]="28th";
    $eachDay["monday5"]="29th";
    $eachDay["tuesday5"]="30th";
    $eachDay["wednesday5"]="31st";

}

我想知道是否有人可以帮我把它浓缩成一个循环?代码太长太乱了,我很想把它缩短

4

1 回答 1

0

一种可能的实现,假设它的 perl

use strict;

sub dayHash {
  my $firstDayOfMonth = lc(shift);
  my @days = qw(monday tuesday wednesday thursday friday saturday sunday);
  my $start = -1;
  my $i;
  for ( $i = 0; $i < $#days; $i++ ) {
    if ( $firstDayOfMonth eq $days[$i] ) {
      $start = $i;
      last;
    }
  }
  my %eachDay = ();
  my $suffix = 1;
  my $key;
  my $val;
  for ( $i = 1; $i <= 31; $i++ ) {
    $key = "$days[$start++]$suffix";
    if ( $start > $#days ) {
      $start = 0;
      $suffix++;
    }
    if ( ($i % 10) == 1 && int($i / 10) != 1 ) {
      $val = $i. 'st';
    } elsif ( ($i % 10) == 2 && int($i / 10) != 1 ) {
      $val = $i . 'nd';
    } elsif ( ($i % 10) == 3 && int($i / 10) != 1 ) {
      $val = $i . 'rd';
    } else {
      $val = $i . 'th';
    }
    $eachDay{$key} = $val;
  }
  return %eachDay
}
my $firstDayOfMonth = "Monday";
my %eachDay = dayHash($firstDayOfMonth);
于 2013-08-06T10:05:43.757 回答