Skip to content

Instantly share code, notes, and snippets.

@rdmarsh
Last active June 1, 2016 04:17
Show Gist options
  • Save rdmarsh/5ae964b4db692ebfbd7e3cd6e0d5ac5d to your computer and use it in GitHub Desktop.
Save rdmarsh/5ae964b4db692ebfbd7e3cd6e0d5ac5d to your computer and use it in GitHub Desktop.
simple example to center text on a line
#!/usr/bin/env perl -w
### 2016-06-01:davidm:simple program to center text on a line
use strict;
use warnings;
use POSIX;
#f1: string
#f2: total width
#f3: left border char
#f4: right border char
#f5: pad char
cent('t', 8, ':', ':', '.');
cent('te', 8, ':', ':', '.');
cent('tes', 8, ':', ':', '.');
cent('test', 8, ':', ':', '.');
cent('testt', 8, ':', ':', '.');
cent('testte', 8, ':', ':', '.');
cent('testtes', 8, ':', ':', '.');
cent('testtest', 8, ':', ':', '.');
cent('testtestt', 8, ':', ':', '.');
cent('t', 8, '', '', '.');
cent('te', 8, '', '', '.');
cent('tes', 8, '', '', '.');
cent('test', 8, '', '', '.');
cent('testt', 8, '', '', '.');
cent('testte', 8, '', '', '.');
cent('testtes', 8, '', '', '.');
cent('testtest', 8, '', '', '.');
cent('testtestt', 8, '', '', '.');
cent('t', 8, '>', '<' );
cent('te', 8, '>', '<' );
cent('tes', 8, '>', '<' );
cent('test', 8, '>', '<' );
cent('testt', 8, '>', '<' );
cent('testte', 8, '>', '<' );
cent('testtes', 8, '>', '<' );
cent('testtest', 8, '>', '<' );
cent('testtestt', 8, '>', '<' );
cent('t', 8);
cent('te', 8);
cent('tes', 8);
cent('test', 8);
cent('testt', 8);
cent('testte', 8);
cent('testtes', 8);
cent('testtest', 8);
cent('testtestt', 8);
sub cent {
my $centertxt = shift;
my $linewid = shift;
my $lefttxt = shift;
my $righttxt = shift;
my $padchar = shift;
$centertxt = ' ' if not defined $centertxt;
$linewid = 80 if not defined $linewid;
$lefttxt = '' if not defined $lefttxt;
$righttxt = '' if not defined $righttxt;
$padchar = ' ' if not defined $padchar;
my $centerlen = length($centertxt);
my $leftlen = length($lefttxt);
my $rightlen = length($righttxt);
my $topad = $linewid - $centerlen - $leftlen - $rightlen;
if ($topad < 0 ) {
$topad = 0;
}
$linewid = $linewid - $topad;
my $leftpad = ( $padchar x floor($topad / 2 ) );
my $rightpad = ( $padchar x ceil($topad / 2 ) );
print "${lefttxt}${leftpad}${centertxt}${rightpad}${righttxt}\n"
}
@rdmarsh
Copy link
Author

rdmarsh commented Jun 1, 2016

Output looks like:

$ ./centertext.pl 
:..t...:
:..te..:
:.tes..:
:.test.:
:testt.:
:testte:
:testtes:
:testtest:
:testtestt:
...t....
...te...
..tes...
..test..
.testt..
.testte.
testtes.
testtest
testtestt
>  t   <
>  te  <
> tes  <
> test <
>testt <
>testte<
>testtes<
>testtest<
>testtestt<
   t    
   te   
  tes   
  test  
 testt  
 testte 
testtes 
testtest
testtestt
$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment