I just finished working on a solution for the exercises provided in the tutorial located here:
A Beginner's Introduction to Perl 5.10 - Perl.com http://bit.ly/dHvsqC (shortened to prevent cutoff) Instructions for the exercise: "Given a month and the day of the week that's the first of that month, print a calendar for the month." and would like to request feedback on the solution with regards to ways I could potentially improve this code. Also any mention of perldocs or other documentation to look over would be most appreciated. Thank you ahead of time for any feedback. Note: Leap year logic is intentionally left out to make sure I understood the basics. === Code === use warnings; use strict; use List::Util qw(first); my %days_in_months = ( 'Jan' => 31, 'Feb' => 29, 'Mar' => 31, 'Apr' => 30, 'May' => 31, 'Jun' => 30, 'Jul' => 31, 'Aug' => 31, 'Sep' => 30, 'Nov' => 31, 'Dec' => 31 ); my @days_of_the_week = ('Sun','Mon', 'Tue', 'Wed', 'Thu', 'Fri','Sat'); sub PrintHeaders { print "Sun\tMon\tTue\tWed\tThu\tFri\tSat\n"; } sub GetDayOfWeekIndex { my $day_of_the_week_name = shift; my $index_value = first { $days_of_the_week[$_] eq $day_of_the_week_name } 0 .. $#days_of_the_week; return $index_value; } sub PrintCalendar { my($month, $start_day) = @_; my $start_day_of_the_week = GetDayOfWeekIndex $start_day; my $day_of_week_counter = 0; # If the first day of the week doesn't start on Sunday # we will need to add some visual padding. if($start_day_of_the_week != $day_of_week_counter) { # -1 is used here because we need to loop this for # the days up to but not including the start day of # the week for my $i (0..($start_day_of_the_week-1)) { print "\t"; } $day_of_week_counter = $start_day_of_the_week; } for my $day (1..$days_in_months{$month}) { print $day; if($day_of_week_counter == $#days_of_the_week) { print "\n"; $day_of_week_counter = 0; } else { print "\t"; $day_of_week_counter++; } } ## end for } PrintHeaders; PrintCalendar "Jan", "Fri"; == Output == Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 (Verified by looking at a calendar for January 2010 with Friday as the first day of the week.) -- Onteria Will you change the world, or will the world change you?
signature.asc
Description: OpenPGP digital signature