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

hey everyone im trying to print a hash into a table so one shows the keys and the other the values but what im trying isn't working right now, this is what I have right now im not putting in all the code cause a lot of it is useless so im only showing the hash bits

my($words, %everything); my @countKey = keys %everything; my @countValue = values %everything; foreach my $word(split /\s+/, $input) { $everything {$word}++; $words++; } foreach $word(keys %everything) { print "$word was seen $everything{$word} times\n"; } print start_table({-border=>1}); print Tr(td('Keys'), td('Values')); print Tr(td(print("@countKey")), td(@countValue)); print end_table;

Replies are listed 'Best First'.
Re: printing a hash into a table
by hippo (Archbishop) on Mar 03, 2019 at 22:54 UTC
    but what im trying isn't working right now

    That's hardly a complete description of the problem. Printing all the hash entries is essentially trivial with each:

    while (my ($key, $value) = each %everything) { print "<tr><td>$key</td><td>$value</td></tr>"; }

      ahh that worked thank you, is there a way to use that to print out say like the first 5 elements of the hash?

        is there a way to use that to print out say like the first 5 elements of the hash?
        That would probably not make too much sense, since hashes are not keeping any order.

        Update: fixed a typo.

Re: printing a hash into a table
by AnomalousMonk (Archbishop) on Mar 03, 2019 at 22:57 UTC
    my($words, %everything); my @countKey = keys %everything; my @countValue = values %everything;

    Declare a hash; fill two arrays with the keys and values of the empty hash (i.e., no keys or values).

    foreach my $word(split /\s+/, $input) { $everything {$word}++; $words++; }

    Put stuff in the hash.

    foreach $word(keys %everything) { print "$word was seen $everything{$word} times\n"; }

    Print the keys and values of the now non-empty hash.

    print start_table({-border=>1}); print Tr(td('Keys'), td('Values')); print Tr(td(print("@countKey")), td(@countValue)); print end_table;

    Use the contents of the still empty arrays previously filled from what was an empty hash to build a table.


    Give a man a fish:  <%-{-{-{-<