Search code examples
perltext

How to empty the $table every iteration drawn using Text::SimpleTable


#!/tool/pandora64/bin/perl5.18.1
use strict;
use warnings;
use Text::SimpleTable; my $a=1;my $b=2; my $c=3; my $d=4; my @p_arr = (1,2);
my $table = Text::SimpleTable->new([1, "A"], [2, "B"], [3, "C"], [4, "D"]);
foreach my $p(@p_arr){
    $table->row($a,$b,$c,$d);
    $a=$a+1; $b=$b+1; $c=$c+1; $d=$d+1;
    print "\nAfter $p iteration\n";
    print $table->draw;
}

I need to print the table, but after the first iteration it is appending. How can I empty the table after every iteration?

Output I get:

After 1 iteration
.----+----+-----+------.
| A  | B  | C   | D    |
+----+----+-----+------+
| 1  | 2  | 3   | 4    |
'----+----+-----+------'

After 2 iteration
.----+----+-----+------.
| A  | B  | C   | D    |
+----+----+-----+------+
| 1  | 2  | 3   | 4    |
| 2  | 3  | 4   | 1    |
'----+----+-----+------'

Expected after 1st iteration:

.----------------
| A | B | C | D |
+----------------
| 1 | 2 | 3  | 4 |
+----------------

Expected 2nd iteration:

.----------------
| A | B | C | D |
+----------------
| 2 | 3 | 4 | 5 |

Solution

  • Simply move the call to new inside the foreach loop. This creates a new table each time through the loop:

    use strict;
    use warnings;
    use Text::SimpleTable; my $a=1;my $b=2; my $c=3; my $d=4; my @p_arr = (1,2);
    foreach my $p(@p_arr){
        my $table = Text::SimpleTable->new([1, "A"], [2, "B"], [3, "C"], [4, "D"]);
        $table->row($a,$b,$c,$d);
        $a=$a+1; $b=$b+1; $c=$c+1; $d=$d+1;
        print "\nAfter $p iteration\n";
        print $table->draw;
    }
    

    Prints:

    After 1 iteration
    .----+----+-----+------.
    | A  | B  | C   | D    |
    +----+----+-----+------+
    | 1  | 2  | 3   | 4    |
    '----+----+-----+------'
    
    After 2 iteration
    .----+----+-----+------.
    | A  | B  | C   | D    |
    +----+----+-----+------+
    | 2  | 3  | 4   | 5    |
    '----+----+-----+------'
    

    If you want the width of all the columns to be the same, you can use the same number in the call to new:

    my $table = Text::SimpleTable->new([1, "A"], [1, "B"], [1, "C"], [1, "D"]);
    

    The POD doesn't specify what the arguments to new are, so I had to look at the source code.