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

Hi, Why the second while function don't work

my %weekday=( 1 => "Monday", 2 => "Tuesday", 3 => "Wednesday", 4 => "Thursday", 5 => "Friday", 6 => "Saturday", 7 => "Sunday", ); while ( (my @all )=each(%weekday) ) { say "@all"; } while ( each(%weekday) ) { say; }

Thanks in advance, Adrian

Update: I figure out how the each function is working: "Every time the each function is called, it grabs an element out of the hash and puts them ..." Shame me for the question Adrian

Replies are listed 'Best First'.
Re: each function
by tobyink (Canon) on Jun 03, 2014 at 17:27 UTC

    There are very good reasons to avoid using each entirely.

    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

      Thanks, it help me alot.

Re: each function
by choroba (Cardinal) on Jun 03, 2014 at 13:42 UTC
    What do you mean by "don't work"? say without a parameter prints $_ (and $\), but neither while nor each assign to $_, so you are just getting a bunch of empty lines, one for each key of the hash.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      Elaborating: each returns a key/value pair, so you need to:

      while (my ($k,$v) = each %hash)

      Though in a scalar context, each returns just the key, but I think keys is more readable:

      for (keys %hash)
Re: each function
by AnomalousMonk (Archbishop) on Jun 03, 2014 at 19:39 UTC

      Sorry for "deleting the original content", it was by mistake, I didn't know how to add a reply.

A reply falls below the community's threshold of quality. You may see it by logging in.