trickyq has asked for the wisdom of the Perl Monks concerning the following question:

This node falls below the community's threshold of quality. You may see it by logging in.

Replies are listed 'Best First'.
Re: the final thorn in your toe
by runrig (Abbot) on Jun 05, 2012 at 22:41 UTC
    You have one $row variable, and you use it for both reading and writing the data. So data is read from and written to the same row. Maybe you should have a second variable for writing the rows (call it something besides $row), and only increment it when you have written a row?
Re: the final thorn in your toe
by roboticus (Chancellor) on Jun 05, 2012 at 22:43 UTC

    trickyq:

    If you want to build the sheet in order, then you may find it simpler to build your data in an array, then at the final step, write the table to a spreadsheet. Something like:

    #!/usr/bin/perl use strict; use warnings; use Spreadsheet::WriteExcel; # First build your data table in an array my @T; while (<DATA>) { chomp; + my ($row, $col, $val) = split /,\s*/, $_; last if ! defined $col; $T[$row][$col] = $val; } my $WB = Spreadsheet::WriteExcel->new("FOO.xls"); my $WS = $WB->add_worksheet("FRED"); # Then write the data into your spreadsheet in order for (my $row=0; $row<@T; ++$row) { next if !defined $T[$row]; for (my $col=0; $col < @{$T[$row]}; ++$col) { if (defined $T[$row][$col]) { $WS->write($row, $col, $T[$row][$col]); print "T[$row][$col] = $T[$row][$col]\n"; } } } __DATA__ 1, 2, banana 0, 0, Cell A1 0, 7, bazooka 3, 3, Cell D4 1, 1, apple 7, 0, flooglehorn

    As you can see, the data is in a random order, but it writes it out in the desired order:

    $ perl 974548.pl T[0][0] = Cell A1 T[0][7] = bazooka T[1][1] = apple T[1][2] = banana T[3][3] = Cell D4 T[7][0] = flooglehorn

    And if you want to prevent skipped lines, keep a separate variable for the output row:

    # Then write the data into your spreadsheet in order my $out_row=0; for (my $row=0; $row<@T; ++$row) { next if !defined $T[$row]; for (my $col=0; $col < @{$T[$row]}; ++$col) { if (defined $T[$row][$col]) { $WS->write($out_row, $col, $T[$row][$col]); print "T[$out_row][$col] = $T[$row][$col]\n"; } } ++$out_row; }

    Those changes give you:

    $ perl 974548.pl T[0][0] = Cell A1 T[0][7] = bazooka T[1][1] = apple T[1][2] = banana T[2][3] = Cell D4 T[3][0] = flooglehorn

    Update: Forgot to implement the bit to prevent skipped rows on the first pass. Just added it to the end.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

    A reply falls below the community's threshold of quality. You may see it by logging in.