in reply to X, Y Table structure

You could avoid loading the entire table into memory by doing two reads («SELECT MAX(size)» and «SELECT qty, size, price ORDER BY qty ASC, size ASC»).

my $max_size = 5; # SELECT MAX(size) print("<table>"); print("<tr>"); print("<th>"); print("<th>Sizes"); print("<tr>"); print("<th>QTY"); for my $size (1..$max_size) { print("<th>$size"); } my $last_qty; my $last_size; for ( # SELECT qty, size, price ORDER BY qty ASC, size ASC [ 100, 1, 43 ], [ 100, 2, 45 ], [ 100, 3, 50 ], [ 200, 4, 55 ], [ 250, 1, 52 ], [ 250, 2, 55 ], [ 250, 3, 56 ], [ 250, 5, 61 ], ) { my ($size, $qty, $price) = @$_; if (!defined($last_qty) || $qty != $last_qty) { if (defined($last_size)) { print("<td>") for $last_size+1 .. $max_size; $last_size = 0; } print("<tr>"); print("<th>$qty"); $last_qty = $qty; } print("<td>") for $last_size+1 .. $size-1; print("<td>\$$price"); } if (defined($last_size)) { print("<td>") for $last_size+1 .. $max_size; } print("</table>");

But it's simpler to just loading everything into memory.

use List::Util qw( max ); my %table; my $max_size = 0; for ( # SELECT qty, size, price [ 100, 1, 43 ], [ 250, 1, 52 ], [ 100, 2, 45 ], [ 250, 2, 55 ], [ 100, 3, 50 ], [ 250, 3, 56 ], [ 200, 4, 55 ], [ 250, 5, 61 ], ) { my ($qty, $size, $price) = @$_; $table{$qty}[$size] = $price; $max_size = $size if $size > $max_size; } print("<table>"); print("<tr>"); print("<th>"); print("<th>Sizes"); print("<tr>"); print("<th>QTY"); for my $size (1..$max_size) { print("<th>$size"); } for my $qty (sort { $a <=> $b } keys(%table)) { print("<tr>"); print("<th>$qty"); for my $size (1..$num_cols) { print("<td>", defined($table{$qty}[$size]) ? "\$$table{$qty}[$si +ze]" : ''); } } print("</table>");

Replies are listed 'Best First'.
Re^2: X, Y Table structure
by Anonymous Monk on May 10, 2011 at 01:53 UTC

    Thanks

    The second example was very close to what I want, as sizes aren't always 1,2,3,4 there might be a skipped size some where so I had to alter it a little bit

    Here's my modified code:

    my %table; my %sizes; for ( # SELECT qty, size, price [1, 100, 1, 43 ], [2, 250, 1, 52 ], [3, 100, 2, 45 ], [4, 250, 2, 55 ], [5, 100, 3, 50 ], [6, 250, 3, 56 ], [7, 200, 4, 55 ], [8, 250, 5, 61 ], ) { my ($id,$qty, $size, $price) = @$_; $table{$qty}[$size] = { 'id' => $id, 'price' => $price }; $sizes{$size}++; } print("<table border='1'>"); print("<tr>"); print("<th></th>"); print("<th>Sizes</th>"); print("</tr>"); print("<tr>"); print("<th>QTY"); for my $size (sort {$a <=> $b } keys %sizes) { print("<th>$size"); } for my $qty (sort { $a <=> $b } keys(%table)) { print("<tr>"); print("<th>$qty"); for my $size (sort {$a <=> $b } keys %sizes) { print("<td>", defined($table{$qty}[$size]) ? "<a href='$table{$q +ty}[$size]->{id}'>\$$table{$qty}[$size]->{price}</a>" : ''); } } print("</table>");
    Please give me your thoughts

    Thanks in advance.