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

I have a perl question for y'all, this program:
#!/usr/bin/perl my %days_in_month = ( "Jan" => 31, "Feb" => 29, "Mar" => 31, "Apr" => 30, "May" => 31, "Jun" => 30, "Jul" => 31, "Aug" => 31, "Sep" => 30, "Oct" => 31, "Nov" => 30, "Dec" => 31 ); foreach $day (%days_in_month) { print "$days_in_month{$day} days hath $day\n"; }
gives this output:
[ceidem@SHARPAM ~/src/perl]$ cal.pl 31 days hath Oct days hath 31 31 days hath Dec days hath 31 31 days hath Mar days hath 31 29 days hath Feb days hath 29 31 days hath Jan days hath 31 30 days hath Nov days hath 30 31 days hath May days hath 31 31 days hath Aug days hath 31 30 days hath Sep days hath 30 31 days hath Jul days hath 31 30 days hath Apr days hath 30 30 days hath Jun days hath 30 [ceidem@SHARPAM ~/src/perl]$

Where does the extraneous "days hath n" come from?

TIA,

- chris

New title per NTC - dvergin 2002-05-01

Replies are listed 'Best First'.
Re: dumb newbie question about hashes and printing from a foreach loop
by Molt (Chaplain) on May 01, 2002 at 15:08 UTC

    Common and easy mistake.. you're going through each element in your foreach so you're getting both the keys and the values, as if it were an array rather than a hash.

    To fix it simply change it to foreach $day (keys %days_in_month. This will only get the keys.

Re: dumb newbie question about hashes and printing from a foreach loop
by broquaint (Abbot) on May 01, 2002 at 15:16 UTC
    Where does the extraneous "days hath n" come from?
    It comes from a hash value being used as a key. This is because when a hash is in a list context it evaluates to a list of it's keys and values in alternating pairs. So you were iterating through both keys and values, and when the values were used as keys you were getting 'extraneous' output because they had no corresponding value in the hash. What you intended to do was this.
    foreach my $day (keys %days_in_month) { print "$days_in_month{$day} days hath $day\n"; }
    You'll probably want to read up on types in perl and how to use them effectively.
    HTH

    _________
    broquaint

Re: dumb newbie question about hashes and printing from a foreach loop
by perlplexer (Hermit) on May 01, 2002 at 15:12 UTC
    You are iterating over both keys and values of %days_in_month.
    To fix, add "keys" in front of %days_in_month
    foreach $day (keys %days_in_month) { print "$days_in_month{$day} days hath $day\n"; }
    --perlplexer
Re: Printing a hash from a foreach loop
by abaxaba (Hermit) on May 01, 2002 at 18:34 UTC
    You should try using each:
    while (my ($length,$month) = each %days_in_month) { print "$length days hath $month\n"; }
    ÅßÅ×ÅßÅ
    "It is a very mixed blessing to be brought back from the dead." -- Kurt Vonnegut
Re: Printing a hash from a foreach loop
by ceidem (Initiate) on May 01, 2002 at 20:10 UTC
    Thank you all, from a true newbie.
    - chris