Reputation: 509
Using: Perl v5.10.1, MySQL 5.5.15, DBI.
I need to deliver end users output from a database via email. They do not want this as an attachment, but in the body.
I'd like to deliver the data in an ascii table and am having issues determining if DBI has built in functions to do this (output similar to querying MySQL from the command line).
Or If I can determine the longest row character length I can use that to build the table. I have a way to get the max item length in an array, but I can't wrap my head around doing it with the query results.
my $spacer_length = (reverse sort { $a <=> $b } map { length($_) } @array)[0];
Upvotes: 1
Views: 966
Reputation: 4743
I'm not sure exactly what you're asking for, but if you're looking for the "max row character length" for a given column of a query result, you can do that with SQL:
SELECT MAX(CHAR_LENGTH(col1)) FROM t1
or if you want all of the rows sorted by the length of the values of col1:
SELECT col1,col2 from t1 ORDER BY CHAR_LENGTH(col1) DESC
you can execute these queries using DBI like this:
# $mysql is your DBI connection info
my $query = $mysql->prepare("SELECT col1,col2 from t1 ORDER BY CHAR_LENGTH(col1) DESC");
$query->execute();
and then iterate through the result rows:
while ( my @result = $query->fetchrow_array ) {
my ($col1,$col2) = @result;
# do stuff with the values
}
and you can print the values as you wish, including like the output from the command line mysql client.
Upvotes: 0
Reputation: 67918
Assuming a generic DBI loop, you could do something like this:
use List::Util qw(max);
...
my @output;
my $max;
while (my @foo = $dbi->fetchrow_array) {
$max = max($max // (), map length, @foo);
push @output, \@foo; # save data for email attachment
}
Using the "defined-or" operator //
to avoid an undef
warning and possible contamination in case of negative values.
Upvotes: 5