I am finding the experimental for_list feature in v5.36 very useful - mostly when combined with the indexed builtin or when processing hashes. However, I do frequently want to process hash pairs sequentially by key (similar to for my $k (sort keys %h) { ... }) so I set about looking for a way to do it in a for_list. The best I've come up with is:
#!/usr/bin/env perl use v5.36; no warnings q/experimental::for_list/; use List::AllUtils qw/pairs unpairs/; my %h = map { ( $_, rand ) } ('a' .. 'z'); for my ($k, $v) ( unpairs (sort { $a->key cmp $b->key } pairs %h) ) { say "$k => $v"; }
which is too verbose to be practical. I noticed reading the doc for key/value pair list functions the following:
NOTE: At the time of writing, the following pair* functions that take a block do not modify the value of $_ within the block, and instead operate using the $a and $b globals instead. This has turned out to be a poor design, as it precludes the ability to provide a pairsort function. Better would be to pass pair-like objects as 2-element array references in $_, in a style similar to the return value of the pairs function. At some future version this behaviour may be added. Until then, users are alerted NOT to rely on the value of $_ remaining unmodified between the outside and the inside of the control block.
I don't understand the issue they're raising, but it does sound like a pairsort is what I need. In the meantime, can anyone suggest a better way to sort the pairs when iterating with a for_list over a hash?

In reply to for_list and sorting key/value hash pairs by ibm1620

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.