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

I'm looking to center a few words of output text in the middle of the screen. My program does a little of this...a little of that and then displays the result. Is there a way to have Perl print out the words in the middle of an average size Windows command window or Linux terminal? I've tried using a series of \t's and \n's to get it right, but that of course only works until the screen has been resized. Does Perl offer any formatting of that type? Any guidance?

Replies are listed 'Best First'.
Re: Formatting screen output
by jmcnamara (Monsignor) on Jan 08, 2002 at 13:57 UTC

    One way to do this is to use a Perl format. See the perlform manpage for details.

    Here is a short example:

    #!/usr/bin/perl -w use strict; my $width = 80; my $format = '@'. ('|' x $width) . "\n"; # Print a centred line using the format # formline($format, "This text is centred."); print $^A; # Print the accumulator $^A = ''; # Clear the accumulator # Print some centred lines using the format # my @a = qw(A hat often beckons snowballs); formline($format x @a, @a); print $^A; # Print the accumulator $^A = ''; # Clear the accumulator __END__ Here is the output: This text is centred. A hat often beckons snowballs

    --
    John.

Re: Formatting screen output
by Juerd (Abbot) on Jan 08, 2002 at 14:04 UTC
    If you know the screen width, you can use formats.
    If you don't, you could get the width from Term::Screen.
    Given the screen width in $width, centering a single line is easy:
    sub centerlines { my $width = shift; print map { ' ' x int($width/2 - length($_)/2) . $_ } @_; } centerlines($width, 'These', 'lines', 'are', 'centered');

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

      The Perl Term::Screen module seems like it would work perfectly, the only problem is that it doesn't come with my default Perl installation. I'm running Windows at the moment and have Activestate Perl installed. I tried downloading the Term::Screen module from CPAN, but the installation failed. Does anyone know of a way I can get this installed on a Windows Perl installation? Thanks in advance.