In the last page we created an anonymous hash and showed how to access it. Here we will continue with this hash.
Let's add another key/value pair to the months hash: days in the month.
my $monthsRef = { "03" => { short => "MR", long => "March", }, "01" => { short => "JA", long => "January", }, "04" => { short => "AP", long =>"April", },
For that we simply enter a new key/value pair under the top level of each month like so:
my $monthsRef = { "03" => { short => "MR", long => "March", days => 31, }, "01" => { short => "JA", long => "January", days => 31, }, "04" => { short => "AP", long =>"April", days => 30, }, "06" => { short => "JE", long => "June", days => 30, }, "02" => { short => "FE", long => "February", days => 28, }, "05" => { short => "MY", long => "May", days => 31, }, "07" => { short => "JL", long => "July", days => 31, }, "12" => { short => "DE", long => "December", days => 31, }, "09" => { short => "SE", long => "September", days => 30, }, "08" => { short => "AU", long => "August", days => 31, }, "10" => { short => "OC", long => "October", days => 31, }, "11" => { short => "NO", long => "November", days => 30, }, };
The code to run:
print "\nDays in each month:\n"; foreach my $k(sort keys %{$monthsRef}) { my $mLength = length($$monthsRef{$k}{long}); print qq/$$monthsRef{$k}{long} \t $$monthsRef{$k}{days}\n/ if ( $mLength >= 7); print qq/$$monthsRef{$k}{long} \t\t $$monthsRef{$k}{days}\n/ if ( $mLength < 7); }
Note we also had to adjust the spacing using $mLength again.
Well, we seem to be getting the hang of things now. But, of course there's always 1 thing outside the box.
February as you know has 29 days in a leap year. Can we allow for that?
Yes of course! All we need to do is add an extra key/value pair in each of the month number blocks:
. . . "02" => { short => "FE", long => "February", days => 28, Ldays => 29, }, "05" => { short => "MY", long => "May", days => 31, Ldays => 0, }, . . .
Then print that as well:
foreach my $k(sort keys %{$monthsRef}) { my $mLength = length($$monthsRef{$k}{long}); print qq/$$monthsRef{$k}{long} \t $$monthsRef{$k}{days} \t $$monthsRef{$k}{Ldays}\n/ if ( $mLength >= 7); print qq/$$monthsRef{$k}{long} \t\t $$monthsRef{$k}{days} \t $$monthsRef{$k}{Ldays}\n/ if ( $mLength < 7); }
That correctly prints the number of days in each month, as well as any values for Ldays.
You might want to add Ldays to just the February block, and that would work, but would result in some warnings. Of course you have use strict; use warnings; in your script, right?. Try it to see for yourself.
That's a good chunk of learning. Remember the above examples work with arrays as well. Practice working with references until you feel more comfortable.
Next we will look at Subroutines & References ...