in reply to Sorting data pulled in by DBI

Everybody has told you how to sort (college, then id), but nobody told you to USE STRICT!!! ;)

Now, some handy short-cuts in Perl programming:

Instead of using the ternery operator twice on each column for each row, you could just handle empty columns in the first check:

$student_name = (defined $row[1]) ? $row[1] : ' '; $student_blah = .... ad naseum
Or you could avoid all that extra typing by utilizing map:
while (my @row = $sth_report->fetchrow_array) { @row = map { $_ || ' ' } @row; # .... rest of code }
Also,the only variable you need is one to store the college (actually, you don't even need that one either! :D) ... the rest can be kept in @row, which can be then stored in a hash whose keys are the colleges, and whose values are the rows of the students (ordered by id) who belong to that college:
my %college; while (my @row = $sth_report->fetchrow_array) { @row = map { $_ || ' ' } @row; my $college = pop @row; push $college{$college}, [@row]; }
And some code to print it back out:
foreach my $college (keys %college) { print "$college:\n"; foreach my $row (@{$college{$college}}) { print "\t", join(', ', @$row),"\n"; } }
Hope this helps. :)

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re2: Sorting data pullled in by DBI
by blakem (Monsignor) on Mar 18, 2002 at 01:41 UTC
    My favorite idiom for defaulting a set of values is:
    # psuedocode $_ = DEFAULT for grep !CONDITION, @VALUES; # as it applies in this situation $_ = ' ' for grep !$_, @row;

    -Blake

      The problem with !$_ (and jeffa's map example), is that it tests for truth, so you also end up substituting any values that match 0 instead of only those that are undef.

      Perhaps you meant to use !defined instead?

          --k.


        Yes, !defined is probably a better CONDITON for the original data... I was merely refactoring the given map code. However, since you probably want the empty string to be defaulted as well, I'd probably use something like:
        $_ = ' ' for grep {!defined or $_ eq ''} @arr;

        -Blake