> Best would be to just add your code to some of the core modules

not that easy I'm still struggling to see the best API for a set of functionals operating on hashes.

for instance my function invert should be renamed because you can do %h2= invert invert %h such that you get the original back. so maybe hash_part or hpart might be better.

To have a real "mathematical" invert one has to consider a special structure relation which is effectively a HoA (simple hashes are "functions" which can only be inverted if they are bijective i.e. have unique values)

DB<131> sub invert { my %h=@_; my %h2; while ( my ($k,$v) = each %h ) { push @{ $h2{$_} } , $k for @$v; } return %h2; } DB<134> %t = (1 => ["e", "c", "a"], 2 => ["b", "d", "f"], 3=>[a] ) => (1, ["e", "c", "a"], 2, ["b", "d", "f"], 3, ["a"]) DB<135> invert %t => ("e", [1], "c", [1], "a", [1, 3], "b", [2], "d", [2], "f", [2]) DB<136> invert invert %t => (1, ["e", "c", "a"], 3, ["a"], 2, ["b", "d", "f"])

Now taking the last use cases we saw, I'm not sure how this special application of invert would help.

AND I had to change the interface, to be chainable.

Originally I was operating on a hash_reference and not a list.

DWIM isn't easy here, prototypes don't allow mixing '%hashes' and LISTs, such that the former is taken as reference.

(One might pass an explicit reference '\%hash' and check if the LIST has just one element. Well not very elegant ...)

Hope you understand my struggles...


In reply to Re^6: inverting hash / grouping values by LanX
in thread inverting hash / grouping values by LanX

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.