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

hiya monks,
I am printing a matrix of numbers out. I am using a hash structure with one key->array, ie. pushing in like this:

push @{$hash{$id}}, scalar @charcounts;
Problem 1: I want all the numbers to line up when printed out.

The values could be 1, 2 or 3 digit numbers. My script is a CGI, so Im guessing
I want to use printf qq(stuff here) but am not sure.

Problem 2: with one of the keys I must iterate over the multiple values in the
array separatley so I can set each of them as a hyperlink pointing to a different
page.I emptied the multiple values into a new array (dereferencing ?) like this:
@values=@{$hash{$id}};
Then I used a foreach to go through the array. I was surprised to find loads of extra whitespace
appearing. ie. I put into the values:1 2 3 4 5 6 etc. and out came:1(1 blank space)2(2 blank spaces)3(3 blank spaces).

Problem 3:I also have a problem (unless I turn strict off) when I try to print something for which there were
no values pushed in. I was hoping in these situtations just the key would be printed.

Any ideas?

thanks
basm101

Replies are listed 'Best First'.
Re: hashes of arrays/printf
by davorg (Chancellor) on Mar 24, 2003 at 13:10 UTC
    Problem 1: I want all the numbers to line up when printed out.
    The values could be 1, 2 or 3 digit numbers. My script is a CGI, so Im guessing I want to use printf qq(stuff here) but am not sure.

    printf may not be useful to you here as (I think) you're outputting HTML, so whitespace will be ignored. Have you considered using a table?

    Problem 2: with one of the keys I must iterate over the multiple values in the array separatley so I can set each of them as a hyperlink pointing to a different page.I emptied the multiple values into a new array (dereferencing ?) like this:
    @values=@{$hash{$id}};
    Then I used a foreach to go through the array. I was surprised to find loads of extra whitespace appearing. ie. I put into the values:1 2 3 4 5 6 etc. and out came:1(1 blank space)2(2 blank spaces)3(3 blank spaces).

    That's almost certainly going to be a problem with the code you're using to display the data. Can't help much without seeing it.

    Problem 3:I also have a problem (unless I turn strict off) when I try to print something for which there were no values pushed in. I was hoping in these situtations just the key would be printed.

    Then only print the values if they are defined. Something like this:

    foreach (keys %hash) { print "$_ : "; print "$hash{$_}" if defined $hash{$_}; }
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg