amit kumar
amit kumar

Reputation: 11

How can I get the length of the longest value in a CSV column?

I am new to Perl. I'm stuck formatting and displaying the data. I need to read the data from CSV file and print it on screen in proper formatting. The width of each column is decided by the maximum length of the element present in the column.

my $file = $ARGV[0] or die; 
open(my $data, '<', $file) or die; 
my $max = 0;

while (my $line = <$data>)  
{ 
    chomp $line; 


# Split the line and store it 
# inside the words array 
my @words = split ", ", $line;   
my @C = split( ",", $line);
#$max = length $C[1];
print ("%08c", "$C[2]\n");
for (my $i = 0; $i <= 2; $i++) 
{ 
    #print "$words[$i] "; 
} 
#print "\n"; 


} 



 print "maximum:max($max)\n";

Upvotes: 1

Views: 265

Answers (1)

brian d foy
brian d foy

Reputation: 132858

The column program can do this (see https://unix.stackexchange.com/q/18861/12567):

$ column -t -s, input.csv
cat            wooly mammoth  lizard
kangaroo       dog            bird
grey squirrel  koala          sea otter

If you want to do that yourself, you need to see all of the values.

The simplest thing might be to make two passes. In the first pass, you'll get the maximum length of each column and store it in @longest. If the next row has a longer value in a column, you replace that value in @longest. At the end, the longest length for each column is in @longest:

open my $fh, '<', 'input.csv' or die ...;

my $csv = Text::CSV_XS->new;

@longest;
while( my $row = $csv->getline( $fh ) ) {
    foreach my $i ( 0 .. $#$row ) {
        my $length = length $row->[$i];
        $longest[$i] = $length if $longest[$i] < $length;
        }
    }

After you have that, you'd go through the lines again and use those widths:

seek $fh, 0, 0; # back to beginning of file
my $template = join ' ', map "%-${_}s", @longest;
print "format: $template\n";

while( my $row = $csv->getline( $fh ) ) {
    printf "$template\n", @$row;
    }

Upvotes: 3

Related Questions