Most Revered Monks,
Given a list of random number: @nlist = (3,24,8,17,23,14,17,9,16,24,25,11,22,14,14,8,19,16,15,8);
And list of candidate hash key: my @key_list = ('A'..'Z');

I wish to classify those number in @nlist into a hash. Where each hash will contain number that has same denominator.

Update: As per Aristotle's notion. This is not LCM (Least Common Multiple) or GCF (Greatest Common Factor), it is just simply denominator, based on first number found.

Finally is to get the following result:
my $VAR1 = { 'A' => [3,24,9,24,15], 'B' => [8,16,8,16,8], 'C' => [17,17], 'D' => [23], 'E' => [14,14,14], 'F' => [25], 'G' => [11,22], 'H' => [19] };
In principle this is how I got those result manually. From @nlist:
I am currently stuck with my code below. I really am not sure how to go about it.
I humbly seek your enlightenment.
#!/usr/bin/perl -w use strict; use Data::Dumper; # This is pre-generated random number list, # size could be much greater than this ( >20) my @nlist = (3,24,8,17,23,14,17,9,16,24,25,11,22,14,14,8,19,16,15,8); # This is a pre-generated key candidate. # It may not be used up all of them # In practice I will create a large key list, # that should be greater than potential hash to be created my @key_list = ('A'..'Z'); my $hoa; foreach my $nlist ( @nlist ) { my @tmpar = ($nlist[0]); my $klist; if ( check_member(\@tmpar,$nlist) == 1 ) { push @tmpar, $nlist; $klist = shift @key_list; push @{$hoa->{$klist}}, @tmpar ; } } print Dumper $hoa ; # -- Subroutine ------ sub check_member { # To check if a value can be a member of an array my ($alist,$snum) = @_; if ( $snum % $alist->[0] == 0 ) { return 1; } return 0; }

Regards,
Edward

In reply to Howto Dynamically Create a Hash? by monkfan

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.