Stuff like this just cries for recursion. Have a look at this:
use strict; use Data::Dumper; my $DATA; while(<DATA>) { chomp; my ($one, $two, $three, $four) = split /\:/, $_; push @{$DATA->{$one}{$two}{$three}}, $four; } print "#", &choice ($DATA), "#"; sub choice { my $structure = shift; my %menu; my $x = 0; if ( ref($structure) eq "HASH" ) { %menu = map { $x++ => $_ } sort keys %{$structure}; } elsif ( ref($structure) eq "ARRAY" ) { %menu = map { $_ => $structure->[$_] } (0..@{$structure}-1); } else { return $structure; } print map { "$_ - $menu{$_}\n" } sort keys %menu; print "select : "; chomp(my $a = <STDIN>); return choice (ref($structure) eq "HASH" ? $structure->{$menu{$a}} + : $structure->[$menu{$a}]); } __DATA__ category1:category2:category3:options categorya:categoryb:categoryc:more options categoryd:categorye:categoryf:even more options
This has several favours: better maintainability, easier to read (imho), supports n level depth and multiple "menus" since you pass the data structure into the function.


holli, /regexed monk/

In reply to Re: Parsing through a menu hash. by holli
in thread Parsing through a menu hash. by yoda54

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.