in reply to Re: Hash sorting
in thread Hash sorting

I wrote a very similar solution, except for the iterations in the @data-building block.
while ( my ($section,$v1) = each %$hash ) { while ( my ($item,$count) = each %$v1 ) { push @data, [$count, $section, $item]; } }
This is not a knee-jerk premature optimization; it is how I think of the loop. I believe that, as an idiom, while/each should be favored over foreach/keys when the key and value are both needed but the order of access does not matter.
And I am evangelizing. :)

Replies are listed 'Best First'.
Re: Re: Re: Hash sorting
by tilly (Archbishop) on May 13, 2003 at 15:38 UTC
    And I believe that whether or not it should be favoured is a matter of who you are dealing with.

    I believe that while/each should not be used unless you understand the subtlety of context coercion that keeps you from exiting the loop early (quick, why when you needed just the section should you *not* just grab $section in scalar context?), understanding that you only have one iterator for the hash (what bug can that lead to?), and being aware what manipulations you cannot do to the hash while you are iterating over it.

    If you don't understand that clearly, or you do not wish to make sure that whoever works with the code understands this highly Perl-specific knowledge clearly, then it is much, much better to just use the foreach/keys method of iteration. (Honestly I have been avoiding having to explain certain aspects of context-coercion by careful selection of idioms, and I needed to double-check that your code as presented was always going to do the right thing...)

    Given that, I could work in a shop which used either idiom and be happy. But if you have people who use Perl only sometimes, and do lots with other languages, then I would suggest sticking with the foreach/keys method since there are fewer Perl-specific things that they have to remember to avoid getting burned in confusing ways.

Re^3: Hash sorting
by Aristotle (Chancellor) on May 13, 2003 at 14:06 UTC

    I agree entirely. I've been baffled by how many people either never think of each or even say they actively avoid it. Especially when you're doing several lines of work with each pair, I find the each form moderately to significantly less noisy.

    Although I'd've named $v1 something like $itemcount. :)

    Makeshifts last the longest.