G'day audioboxer,

How you intend to use the data should really drive your choices for data structures. Unfortunately, you've only shown how you currently create the data structure but not its usage. Probably the most important thing to note — and you may already know this — is that arrays are ordered and hashes are unordered.

Other general considerations include the size of the data and whether the data structure ever changes after initial creation. You should also be asking specific questions; such as "Do you only ever want to access the last category or do you perhaps need a sorted list of all categories?".

Here's a technique for sorting the keys based on "id" values:

$ perl -E ' my %x = (A => { id => 2 }, B => { id => 3 }, C => { id => 1 }); my @sorted = sort { $x{$a}{id} <=> $x{$b}{id} } keys %x; say "Last: $sorted[-1]"; ' Last: B

Given it looks like IDs are referenced more than NAMEs, you might consider changing the general layout of the structure to:

ID => { name => '...', parent_id => ..., }

I'd also suggest taking a look at the core List::Util module. Some of its functions may prove useful; for example, max (for IDs) and first (with descending sort) seem to be likely candidates.

— Ken


In reply to Re: Hash or Array - Logic Help by kcott
in thread Hash or Array - Logic Help by audioboxer

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.