|
Posted by joel on August 28, 2006, 2:28 pm
Please log in for more thread options Thanks for the detailed tips, much more than I expected. I have used
printf but it would require that I write code to determine the maximum
widths of each column (the number of columns and size being variable).
Not big deal but I thought that there may be an even easier way. Perl
is for doing things the easy way, right ;-)
Brian McCauley wrote:
> joel wrote:
> > For any number of rows and columns of a multidimensional array, I would
> > like my printHandler subroutine to print in table format with minimal
> > effort. What is the easiest way of doing this?
> >
> > {
> > ...
> > ...
> > while (my (@array)=($sth->fetchrow_array()))
>
> All those parentheses don't really add clarity...
>
> while (my @array = $sth->fetchrow_array )
>
> > {
> > push(@result,[@array]);
> > }
>
> Since @array is declared within the loop (good!) you don't need to make
> a copy of it, you can push a reference to @array itself as you'll get a
> new @array on the next iteration.
>
> push(@result,\@array);
>
> > &printHandler(@result);
>
> Do you know what the & there does? If not then remove it.
>
> As a general rule you should pass arrays to subroutines using array
> references rather than unrolling the array into a list and passing each
> element of the array as a separate argument.
>
> printHandler(\@result);
>
> BTW: have you considered using fetchall_arrayref?
>
> > sub printHandler
> > {
> > my $i=0;
> > foreach (@_)
> > {
> > print "@\n";
> > $i++;
> > }
> > }
>
> Ouch! You put each element of @_ in turn into $_ and then ignore that
> and hand carft a loop index to use as a subscript.
>
> foreach (@_)
> {
> print "@\n"; # {} strictly redundant
> }
>
> Or if you'd passed an array ref...
>
> my ($list)= @_;
> foreach (@$list)
> {
> print "@$_\n";
> }
>
>
> > current output:
> > 4591 05-00371
> > 149817 06-02930
> > 15541 06-0369
> > 827 04-00307
> > 13406 06-01364
> >
> > desired output:
> > 4591 05-00371
> > 149817 06-02930
> > 15541 06-0369
> > 827 04-00307
> > 13406 06-01364
>
> Ah, you want to print the output formatted. Perl has a "print
> formatted" function ..
>
> my ($list)= @_;
> for (@$list)
> {
> printf "%6s %s\n",@$_;
> }
>
> Or if you feel terse..
>
> printf "%6s %s\n",@$_ for @;
|