http://qs1969.pair.com?node_id=403797


in reply to Foreach in a 2D array

Now that you've gotten answers to your question, I figured I'll answer the real question and give an answer that you can't easily read yourself to about data structures.

The first and most interesting part is to redesign the data structure. It seems that you want an ordered list and therefore have an array with the columns, but you also want to have several values attached to that value. My suggestion is that you consider having a data structure looking like

my @data = ( [ Gender => [ 'Male', 'Female'] ], [ A => [ 'a', 'b', 'c'] ], );
which would remove the need for parallel data structures. Your code would then look like
for (@data) { my ($column, $options) = @$_; print $column . ': '; foreach my $option (@$options) { print '<input type="radio" name="' . $column . '" value="' . $ +option . '"> ' . $option . ' '; } }
As a side note, I think that print statement is more clearly written using printf() and another qoute delimiter:
printf qq{<input type="radio" name="%s" value="%s">%s\n}, $column, $option, $option ;
But really, this is unnecessary. CGI already implements a &radio_group subroutine that we can use and get rid of the loop altogether.

The end result is

use strict; use CGI; my $q = CGI::->new; my @data = ( [ Gender => [ 'Male', 'Female'] ], [ A => [ 'a', 'b', 'c'] ], ); for (@data) { my ($column, $options) = @$_; print $q->radio_group( -name => $column, -values => $options, -default => '_', ); # '_' is chosen as default as that will make # no value checked by default, as long as you # don't have '_' as an option. }

If you at any time would like to do a lookup of which values that are accepted for a radio group you can degenerate your @data to %dataoptions by using

my %dataoptions = map @$_, @data;

Related documents:
perlref - Perl references and nested data structures
perlfunc - Perl builtin functions (look for map)
CGI - Simple Common Gateway Interface Class

ihb

See perltoc if you don't know which perldoc to read!
Read argumentation in its context!

Replies are listed 'Best First'.
Re^2: Foreach in a 2D array
by monoxide (Beadle) on Nov 02, 2004 at 11:12 UTC
    Thanks for the tips on the data structure, but the reason i have it like that is because there is multiple other arrays and hashs that are related to the columns array that i dont neccesarily call by name. They got deleted out when i was trying to simplify the script so that people would not have to worry about the rest of it. Thanks anyway.