use strict; use warnings; use DateTime; @ARGV == 3 or die "Usage: perl $0 \n"; my $day_of_week = shift; # (1 is Monday, 7 is Sunday) my $month = shift; my $year = shift; $day_of_week =~ m/^[1-7]$/ or die "Invalid day of week: $day_of_week\n"; $month =~ m/^(?:[1-9]|1[012])$/ or die "Invalid month: $month\n"; print last_day_of_week_of_month($day_of_week, $month, $year), "\n"; exit 0; sub last_day_of_week_of_month { my $day_of_week = shift; # (1 is Monday, 7 is Sunday) my $month = shift; my $year = shift; my $last_day_of_month = DateTime->last_day_of_month( year => $year, month => $month ); my $day_of_week_of_last_day_of_month = $last_day_of_month->day_of_week(); my $last_day_of_week_of_month = $last_day_of_month->day() - (($day_of_week_of_last_day_of_month - $day_of_week) % 7); return $last_day_of_week_of_month; }