walkingthecow has asked for the wisdom of the Perl Monks concerning the following question:

Hey guys, I am using information from last, and the output looks like this:

"daamaya pts/3055 10.37.48.88 Thu Sep 18 09:19 still logged in"

I am basically trying to write a script that will look at the date "Thu Sep 18" and give me the year. I know that the 18th was not on a Thursday in 2007, and so on. I am only doing it between 2004-2008. I wrote a little script that kinda does what I am looking for, but trying to figure out how to make it a subroutine, and how to do it better. I am relatively new to hashes, which would explain why I added a,b,c... to the front of months, just for sorting reasons. Anyway, here's my code. Any suggestions would be so greatly appreciated!!

#!/usr/bin/perl -w print "Please input a year: "; chomp ($year=<STDIN>); $k = 0; while ($year <= 2008) { if (($year % 4 == 0) and ($year % 100 != 0) or ($year % 400 == 0)) + { $leap="true"; } else { $leap="false"; } my %months = ( 'aJan' => '31', 'bFeb' => '28', 'cMar' => '31', 'dApr' => '30', 'eMay' => '31', 'fJun' => '30', 'gJul' => '31', 'hAug' => '31', 'iSep' => '30', 'jOct' => '31', 'kNov' => '30', 'lDec' => '31' ); if ($leap eq "true") { $months{'bFeb'} = '29'; } my @array_of_days = ('Thu', 'Fri', 'Sat', 'Sun', 'Mon', 'Tue', 'We +d'); # my $start = $weekdays{$day_name}; foreach $key (sort keys %months) { #print(join(', ',sort keys %months),"\n"); for ($n = 1; $n <= $months{$key}; $n++) { if ($k == 7) { $k = 0; } print "$array_of_days[$k] $key $n $year\n"; $k++; } } $year++; }

Replies are listed 'Best First'.
Re: Question, New To Hashes
by ikegami (Patriarch) on Sep 18, 2008 at 22:58 UTC

    I am relatively new to hashes, which would explain why I added a,b,c... to the front of months, just for sorting reasons.

    my @months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); my %months; @months{ @months } = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ); ... foreach $key (@months) {
Re: Question, New To Hashes
by pjotrik (Friar) on Sep 18, 2008 at 23:15 UTC
    This is how I would do it:
    #!/usr/bin/perl use warnings; use strict; use Date::Manip qw(ParseDate); my @years = (2004..2008); sub find_year { my ($date) = @_; for my $year (@years) { my $date = ParseDate("$date $year"); return $year if $date; } return undef; } my @dates = ("Thu Sep 18", "Wed Sep 7"); for (@dates) { my $year = find_year($_); print "$_ => " . (defined($year) ? $year : "not found" ) . "\n"; }
      Thank you both! The first gave me a better idea of how to deal with hashes, and the second reply really helped me put the code into a subrouting. Again, thank you guys very much!