Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Easier way to cram Date::Calc's Calendar into a 2-D array

by oylee (Pilgrim)
on Aug 07, 2002 at 18:27 UTC ( [id://188422]=perlquestion: print w/replies, xml ) Need Help??

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

Greetings, Monks:

I need to generate a two-dimensional array of days in a given month for a calendar application that I'm writing for work. The code that follows below seems to work, but I am sure there are better/more efficient ways to do it, and was hoping that some of ye enlightened ones could show me the way.. I am parsing the result of Date::Calc module's Calendar function, which looks something like this:
August 2002 Mon Tue Wed Thu Fri Sat Sun 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
and I thought that there has to be an easier way to cram that into a two-D array than the following code:
#!/usr/bin/perl -w use strict; use Date::Calc qw(Calendar); sub parseCalendar { my ($year, $month) = ( scalar(@_) == 2 ) ? @_ : split(' ', `date +"%Y %m"`); my $cal = Calendar($year, $month); my @cal = split(/\n/, $cal); splice(@cal, 0, 3); # get rid of the first three lines (don't need + em); my @rv = map { $_ = substr($_, 1, length); [split /\s{4}|\s{2}/]; } @cal; return @rv; } my @cal = parseCalendar(); my $i = 1; foreach my $cal_line (@cal) { print "Week ", $i++, ":"; foreach my $day (@$cal_line) { $day ||= " "; print "$day "; } print "\n"; }

Many thanks!
Allen

Replies are listed 'Best First'.
Re: Easier way to cram Date::Calc's Calendar into a 2-D array
by DamnDirtyApe (Curate) on Aug 07, 2002 at 18:44 UTC
    #! /usr/bin/perl use strict ; use warnings ; $|++ ; use Date::Calc qw( Calendar ) ; use Data::Dumper ; my $cal = Calendar( 2002, 8 ) ; my @arr = map { [ split ] } grep { /^[\d\s]+$/ } split /\n/, $cal ; unshift @{$arr[ 0]}, undef until @{$arr[ 0]} == 7 ; push @{$arr[-1]}, undef until @{$arr[-1]} == 7 ; print Dumper( \@arr ) ; __END__
    Update: Added unshift and push to make sure first and last rows have seven days.
    _______________
    DamnDirtyApe
    Those who know that they are profound strive for clarity. Those who
    would like to seem profound to the crowd strive for obscurity.
                --Friedrich Nietzsche
      Neato -- that works great. Thanks!

Re: Easier way to cram Date::Calc's Calendar into a 2-D array
by vek (Prior) on Aug 07, 2002 at 19:38 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://188422]
Approved by Ovid
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2024-04-16 13:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found