Hello Monks,
my @array=(['john','tom','peter'],['rose','teak'],['car','truck','jeep +'],['trees','plants'],['good','bad','ugly']); my @arrayindex=(3,1); my %hash=(); foreach my $i (@{$array[$arrayindex[0]]}) { foreach my $j (@{$array[$arrayindex[1]]}) { $hash{"$i $j"}=1; } } foreach my $i (keys %hash) { print "$i=>$hash{$i}\n"; } The output of the program is a hash whose keys represent all possible +combination of values: trees rose=>1; trees teak=>1; plants rose=>1; plants teak=>1;
However, I do not know how to handle variable number of elements in @arrayindex, because the above code is rigid and can only work for exactly two elements in @arrayindex (such as @arrayindex=(3,1)). I want the code to be generic so that it can handle any number of elements in @arrayindex, such as, @arrayindex=(3,0,1), @arrayindex=(3,1), @arrayindex=(4,2,1,5), or @arrayindex=(2) etc. Please advise how this can be done. My thinking here was to create the number of foreach loops dynamically, however, don't know if that is even possible. Thank you guys, Raj

In reply to Advice on loops by newbio

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.