sub build_huffman_tree { my ($dict_hash)= @_; # @node constains either: # leafs: [ $non_ref_symbol, $count ] # nodes: [ [ $left_node, $right_node ], $left_count + $right_count ]; # note we assume the counts in the hash are > 0. my @nodes= map { [ $_, $dict_hash->{$_} ] } keys %$dict_hash; while (@nodes > 1) { @nodes= sort { $b->[1] <=> $a->[1] } @nodes; my $right= pop @nodes; my $left= pop @nodes; push @nodes, [ [ $left, $right ], $left->[1] + $right->[1] ]; } return $nodes[0]; }