Text allignment using PERL

Hi Friends,

For daily reports i make perl script like below.

@dirlist = `cat out.txt |cut -d "|" -f1 >create.txt`; 

@dirlist1 = `cat out.txt|wc -l *e* >create2.txt`;

open FILE, ">OUTPUT.txt";
@command = `cat out.txt |cut -d "|" -f1`; print FILE map{$_-2 ."\n"}@command;

@dirlist2 = `paste create.txt create2.txt OUTPUT.txt > exeout.txt`;

@dirlist3= `cat exeout.txt`;

print "@dirlist3";

output is :

378462         4 allignment.pl   378460
 764jds         3 create.txt      762
 907834        0 create2.txt     907832
                  8 exeout.txt
                  21 test.pl
                  11 test2.pl
                  8 test3.pl
                   55 total

i expect the out put in correct allignment with table. we can give coloum name like col-1 col-2 col-3

First things first: Perl is not shell scripting!
Second: you're using cat far too often. cut can read a file fine by itself, and wc, when given a file argument, won't even bother reading stdin.
Third: see perldoc perlform for Perl formatting instructions, which are ideal for report formatting.

---------- Post updated at 09:45 ---------- Previous update was at 09:29 ----------

(Almost) exactly your script, except without temporary files, pretty printing, and only 1 external call:

#!/usr/bin/perl

use strict;
use warnings;

my ( @dirlist, @dirlist1, @command );
my ( $dir,     $dir1,     $cmd );

format STDOUT_TOP=
+----------+---------------------+---------+
| Col 1    | Col 2               | Col 3   |
+----------+---------------------+---------+
.

format STDOUT=
| @<<<<<<< | @|||||||||||||||||| | @>>>>>>>|
  $dir,      $dir1,                $cmd
.

format STDOUT_BOTTOM=
+----------+---------------------+---------+
.

open my $fh, '<', 'out.txt';
@dirlist = map { @_ = split /\|/; $_[0] } <$fh>;
close $fh;
@command = map { $_ - 2 } @dirlist;
@dirlist1 = split /\n/, qx/wc -l *e*/;

for ( my $i = 0 ; $i < scalar @dirlist1 ; $i++ ) {
    $dir  = $dirlist[$i];
    $dir  = '' unless defined $dir;
    $dir1 = $dirlist1[$i];
    $dir1 = '' unless defined $dir1;
    $cmd  = $command[$i];
    $cmd  = '' unless defined $cmd;
    write;
}
$~ = 'STDOUT_BOTTOM';
write;

Will result in:

+----------+---------------------+---------+
| Col 1    | Col 2               | Col 3   |
+----------+---------------------+---------+
| 378462   |      3 test1.txt    |   378460|
| 764      |      6 test2.txt    |      762|
| 907834   |      1 test3.txt    |   907832|
|          |       10 total      |         |
+----------+---------------------+---------+

And you can adjust the formatting as you like, without having to change the whole code.

1 Like