J
January Weiner
Hi,
I run into this basic problem now and then.
Hashes allow you to access an element by a key. However, hashes are not
ordered. Take the following example: I have a hash containing a menu
structure:
my %menu = ( -file => [ "new", "open", "save" ],
-analize => [ "count", "add", "subtract" ],
-help => [ "yelp", "cry", "bang your head on the wall" ],
) ;
Now I have some arbitrary function that should display this menu. However,
the order should be preserved, and there is no way we could order it
automatically (e.g. alphabetically). I see two solutions:
1) create a menu index:
my @menu_idx = ( "-file", "-analize", "-help" ) ;
for(@menu_idx) {
do_something($menu{$_}) ;
}
2) pretend %menu is an array:
my @menu = ( "-file", [ "new", "open", "save" ],
"-analize", [ "count", "add", "subtract" ],
"-help", [ "yelp", "cry", "bang your head on the wall" ],
) ;
my %menu_hash = @menu ;
for($i = 0 ; $i < scalar(@menu) ; $i += 2) {
do_something($menu_hash{$menu[$i]}) ;
}
Neither seems to be satisfactory. Are there better ways of dealing with
this problem?
j.
--
I run into this basic problem now and then.
Hashes allow you to access an element by a key. However, hashes are not
ordered. Take the following example: I have a hash containing a menu
structure:
my %menu = ( -file => [ "new", "open", "save" ],
-analize => [ "count", "add", "subtract" ],
-help => [ "yelp", "cry", "bang your head on the wall" ],
) ;
Now I have some arbitrary function that should display this menu. However,
the order should be preserved, and there is no way we could order it
automatically (e.g. alphabetically). I see two solutions:
1) create a menu index:
my @menu_idx = ( "-file", "-analize", "-help" ) ;
for(@menu_idx) {
do_something($menu{$_}) ;
}
2) pretend %menu is an array:
my @menu = ( "-file", [ "new", "open", "save" ],
"-analize", [ "count", "add", "subtract" ],
"-help", [ "yelp", "cry", "bang your head on the wall" ],
) ;
my %menu_hash = @menu ;
for($i = 0 ; $i < scalar(@menu) ; $i += 2) {
do_something($menu_hash{$menu[$i]}) ;
}
Neither seems to be satisfactory. Are there better ways of dealing with
this problem?
j.
--