vennirajan has asked for the wisdom of the Perl Monks concerning the following question:

Dearest Monks,

I have written a piece of code to produce a sort of "Cartesian Product" of the data structure. But the code produces the strange output. Can any one tell me what is happening ?

my %data = ( "one" , 1, "two",2,"three",3,"four",4,"five",5,"six",6,"s +even",7,"eight",8,"nine",9); my %newData = (); while (my ($key1,$val1) = each(%data)) { if (my ($key,$value) = each(%data)) { $newData{$key1,$key} = "$val1$;$value"; } else { last; } } map { print "$_ : $newData{$_}\n";} keys %newData ;

The output is:
fiveseven : 57 nineeight : 98 twoone : 21 threesix : 36
Thanks in advance.

Regards,
S.Venni Rajan.
"A Flair For Excellence."
                -- BK Systems.

Replies are listed 'Best First'.
Re: What is wrong with the code ?
by japhy (Canon) on Jan 18, 2006 at 08:12 UTC
    The each() function only has ONE iterator per hash. You'll have to use keys().
    for my $k1 (keys %hash) { for my $k2 (keys %hash) { next if $k1 eq $k2 and $skip_identical_keys; $cart_prod{$k1}{$k2} = ...; } }

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
      Do you mean that single pointer will be used for each data structure and that pointer also will be shared ?

      Regards,
      S.Venni Rajan.
      "A Flair For Excellence."
                      -- BK Systems.
        No. %data has one iterator. %foo has one iterator.
Re: What is wrong with the code ?
by GrandFather (Saint) on Jan 18, 2006 at 08:15 UTC

    What do you expect to see? Maybe what you want is to add local $; = ' '; somewhere before the while loop? If you do that the code prints:

    two one : 2 1 nine eight : 9 8 three six : 3 6 five seven : 5 7

    DWIM is Perl's answer to Gödel
Re: What is wrong with the code ?
by NetWallah (Canon) on Jan 18, 2006 at 17:53 UTC
    You may want to look at the Math::Combinatorics module, and see if the nCk combination will produce the result you seek.

         You're just jealous cause the voices are only talking to me.

         No trees were killed in the sending of this message.    However, a large number of electrons were terribly inconvenienced.