Perl Formater for Terminal and HTML

If you want to bring your “ps” or another tabel in a good format you could use this skript:

#!/usr/bin/perl
use strict;
# test tabel
my $var1 = q(
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0 782116 56436 ?        Ssl  14:22   0:03 --NONE--
root         7  0.0  0.0  11728  1348 pts/0    Ss   14:22   0:00 sh
root        61  0.0  0.0  19740  1212 pts/0    R+   15:44   0:00 ps
);
#destroy format
$var1 =~ s/[ ]{1,}/ /go;
$var1 =~ s/^ +//gom;

#test cases
print expand($var1);#terminal
print expand($var1,1);#html

#sub
sub expand {
    my $var = shift;
    my $html = shift//0;
    $var = "n".$var;
    if($html == 0){#terminal
        $var =~ s/([^ ]{1,})/(' 'x(10-length($1))).$1/ge;
    }else{#html
        $var =~ s/^n+//o;
        my @blocks = split(/(?<=n)/o,$var);
        $blocks[0] =~ s![ ]{1,}!</th><th>!go;#title
        $blocks[0] = "<tr><th>".$blocks[0]."</th></tr>";#title end
        for my $i (1..$#blocks){#content loop
            $blocks[$i] =~ s![ ]{1,}!</td><td>!go;#content
            $blocks[$i] = "<tr><td>".$blocks[$i]."</td></tr>";#content end
        }
        $var = join('', @blocks);#rebuild
        $var = "<table>".$var."</table>";#complet end
    }
    return($var);
}

Here we have a good terminal format:

USER        PID       %CPU       %MEM        VSZ        RSS        TTY       STAT      START       TIME COMMAND
root          1        0.0        0.0     782116      56436          ?        Ssl      14:22       0:03 --NONE--
root          7        0.0        0.0      11728       1348      pts/0         Ss      14:22       0:00    sh
root         61        0.0        0.0      19740       1212      pts/0         R+      15:44       0:00        ps

This is the raw HTML output:

<table><tr><th>USER</th><th>PID</th><th>%CPU</th><th>%MEM</th><th>VSZ</th><th>RSS</th><th>TTY</th><th>STAT</th><th>START</th><th>TIME</th><th>COMMAND
</th></tr><tr><td>root</td><td>1</td><td>0.0</td><td>0.0</td><td>782116</td><td>56436</td><td>?</td><td>Ssl</td><td>14:22</td><td>0:03</td><td>--NONE--
</td></tr><tr><td>root</td><td>7</td><td>0.0</td><td>0.0</td><td>11728</td><td>1348</td><td>pts/0</td><td>Ss</td><td>14:22</td><td>0:00</td><td>sh
</td></tr><tr><td>root</td><td>61</td><td>0.0</td><td>0.0</td><td>19740</td><td>1212</td><td>pts/0</td><td>R+</td><td>15:44</td><td>0:00</td><td>ps
</td></tr></table>

And in the browser it looks pretty like this :

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 782116 56436 ? Ssl 14:22 0:03 –NONE–
root 7 0.0 0.0 11728 1348 pts/0 Ss 14:22 0:00 sh
root 61 0.0 0.0 19740 1212 pts/0 R+ 15:44 0:00 ps

Leave a Reply

Your email address will not be published.

3 + 8 =