Markham, Richard wrote:
> this explained just about everything and was 10 times less confusing than my
> own broken code.
> where I really get confused in Perl is different situations will return
> ARRAY reference and
> others will return the element.
>
> as an example (printf is obviously better), if i were to do a
> print @$line . "\n"
> it will return a number so I dont know why that is so.
>
> also the @$line is confusing to me since I thought @ implied a whole array
> thus meaning
> an array reference so I cant seem to explain how @$ works.
Here's a C-like solution that isn't confusing. I assumed you wanted
the columns to line up vertically:
use strict;
use warnings;
my @newmatrix = (["123.45", "JOHN DOE", "Coal Miner"],
["12.45", "MR. PEANUT", "peanut"],
["4.1", "Bill Clinton", "unknown"]);
my @maxlength;
# determine max length of each column
for (my $ii = 0; $ii < @newmatrix; $ii++) {
for (my $jj = 0; $jj < @{$newmatrix[$ii]}; $jj++) {
my $len = length $newmatrix[$ii][$jj];
$maxlength[$jj] = 0 if not defined $maxlength[$jj];
$maxlength[$jj] = $len if $len > $maxlength[$jj];
}
}
# print each row using column widths derived above
for (my $ii = 0; $ii < @newmatrix; $ii++) {
for (my $jj = 0; $jj < @{$newmatrix[$ii]}; $jj++) {
printf "%-*s", $maxlength[$jj] + 2, $newmatrix[$ii][$jj];
}
print "\n";
}
__END__
> use strict;
> use warnings;
>
> my @newmatrix=(
> ["123.45" , "JOHN DOE" , "Coal Miner" ]
> , ["12.45" , "MR. PEANUT" , "peanut" ]
> , ["4.1" , "Bill Clinton" , "unknown" ]
> );
>
> my @maxlength;
> foreach my $line (@newmatrix) {
> my $index = 0;
>
> foreach my $column (@$line) {
> $maxlength[$index] = 0 unless (defined $maxlength[$index]);
>
> if ((length $column) > $maxlength[$index]) {
> $maxlength[$index] = (length $column);
> }
>
> $index++;
> }
> }
>
> my $format = "";
> foreach my $width (@maxlength) {
> $format .= " " if ($format);
>
> $format .= "%-" . $width . "s";
> }
>
> foreach my $line (@newmatrix) {
> printf "$format\n", @$line;
> }
--
,-/- __ _ _ $Bill Luebkert Mailto:[EMAIL PROTECTED]
(_/ / ) // // DBE Collectibles Mailto:[EMAIL PROTECTED]
/ ) /--< o // // Castle of Medieval Myth & Magic http://www.todbe.com/
-/-' /___/_<_</_</_ http://dbecoll.tripod.com/ (My Perl/Lakers stuff)
_______________________________________________
Perl-Unix-Users mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs