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


in reply to Foreach in a 2D array

Remember that a hash is a datastructure where each element has a *key* and a *value*. Looking at your code I think your intent was to create a hash (%dataoptions) that had one key "Gender", and that key "Gender" having a related value that is an array whose elements are "Male" and "Female".

So, this:

my %dataoptions = ( "Gender", ["Male", "Female"] );
should be this:
my %dataoptions = ( "Gender" => ["Male", "Female"] );
The other thing to remember is that this:
["Male", "Female"]
creates a *reference* to an anonymous array. So in hash %dataoptions, the value corresponding to key "Gender" is a *reference* to an anomyous array containing elements "Male" and "Female". So then when you do
foreach $option ($dataoptions{$columns[$i]})
$option is a *reference* to an array.

I think you want your loop to be something like this:

for ($i = 0; $i < @columns; $i++) { print $columns[$i].': '; my $arrayref = $dataoptions{$columns[$i]}; foreach $option (@$arrayref) { print '<input type="radio" name="'.$columns[$i].'" value="'.$ +option.'"> '.$option.' '; } }
HTH.

Replies are listed 'Best First'.
Re^2: Foreach in a 2D array
by osunderdog (Deacon) on Oct 28, 2004 at 13:54 UTC

    This is probably just a minor nit, but thought I might learn something. My understanding is that there is very little difference (from the perl interpreter standpoint) between:

    my %hash = ('a', 'b', 'c', 'd');
    and
    my %hash = ('a' => 'b', 'c'=> 'd');

    Advantages I can think of for the first representation are:

    • As long as you know that a list has an even number of elements, you can use it as a hash.

    The advantages I can think of for the second representation are:

    • The => reads better from a maintainability standpoint
    • you don't have to quote the key. For example:
      my %hash = (a=>'b', c=>'d');

    Essentially => is syntactic sugar for ,.

    Update. Missed a tic.


    "Look, Shiny Things!" is not a better business strategy than compatibility and reuse.


    OSUnderdog
      You're right. Sorry, I was a little quick to correct the "," to "=>", but I think the comma works fine as you pointed out. I'm so used to using "=>" that at first glance I thought using the comma was illegal. The "as long as you know that the list has an even number of elements..." part is enough for me to use the 2nd version ("=>") since I know the 2nd one works all the time :-) In fact all the perl documentation on hashes shows the "=>" operator.

      As I think you'll agree, in this code:

      my %hash = ('a', 'b', 'c', 'd');
      it is not clear that 'a' is the key referring to value 'b'.