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

Hi, i am trying to understand a friends program so that i can continue it, the problem is that dont understand a few lines of his code, can anyone explain them?? He has declared a hash called %freq;
$num = $freq{$array[0]}{"freq"}++; $freq{$array[0]}{"value"}[$num] = $_;
and
my @sorted_array = sort {$freq{$b}{"freq"} <=> $freq{$a}{"freq"}} keys + %freq;
thanks!!

Edit kudra, 2002-06-14 Changed title

  • Comment on Need explanation of frequency counting and ranking in a hash (was: can anyone explain)
  • Select or Download Code

Replies are listed 'Best First'.
Re: can anyone explain
by Abigail-II (Bishop) on Jun 13, 2002 at 09:22 UTC
    What's there to explain? I can tell you what it does, but will that be helpful?
    $num = $freq{$array[0]}{"freq"}++; $freq{$array[0]}{"value"}[$num] = $_;
    It seems that %freq contains a hashref belonging to whatever key is stored in the first element of @array. That hashref has a key "freq", whose old value is stored in $num and is then incremented. The hashref also has a key "value", whose value is an arrayref. On postion $num, $_ is stored. This probably could have been written much simpler as:
    push @{$freq {$array [0]} {value}} => $_;
    my @sorted_array = sort {$freq{$b}{"freq"} <=> $freq{$a}{"freq"}} keys + %freq;
    Here the keys of the hash are sorted, and they are ordered on how many elements there are in the array @{$freq {$array [0]} {value}}

    Abigail

Re: can anyone explain
by marvell (Pilgrim) on Jun 13, 2002 at 09:25 UTC
    Try this example:
    #!/usr/bin/perl use Data::Dumper; $array[0] = "sponge"; for ($_=2;$_<=20;$_+=2) { $num = $freq{$array[0]}{"freq"}++; $freq{$array[0]}{"value"}[$num] = $_; } $array[0] = "wombat"; for (1..5) { $num = $freq{$array[0]}{"freq"}++; $freq{$array[0]}{"value"}[$num] = $_; } my @sorted_array = sort {$freq{$b}{"freq"} <=> $freq{$a}{"freq"}} keys + %freq; print Dumper(\%freq); print "@sorted_array\n";

    For each of the elements sponge and wombat, build a list of values and store the total number of values.

    The sort sorts the keys of the hash (wombat and sponge) by the frequency.

    --
    Steve Marvell

Re: can anyone explain
by Bilbo (Pilgrim) on Jun 13, 2002 at 11:38 UTC