Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve the terminal width in Perl?

Tags:

terminal

perl

I want to output a progress bar, but how do I retrieve the terminal width in Perl?

A core Perl solution would be preferred, since I don't have access to a compiler, just an already installed 5.8.2 Perl.

like image 423
Steve Schnepp Avatar asked Nov 23 '09 09:11

Steve Schnepp


2 Answers

The FAQ which ships with Perl has the answer to this question. If you run perldoc -q "screen size", you'll get the following:

How do I get the screen size?

If you have Term::ReadKey module installed from CPAN, you can use it to fetch the width and height in characters and in pixels:

use Term::ReadKey;
($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();

This is more portable than the raw "ioctl", but not as illustrative:

require 'sys/ioctl.ph';
die "no TIOCGWINSZ" unless defined &TIOCGWINSZ;
open(TTY, "+</dev/tty") or die "No tty: $!";
unless (ioctl(TTY, &TIOCGWINSZ, $winsize='')) {
    die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\n", &TIOCGWINSZ;
}
($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);
print "(row,col) = ($row,$col)";
print "  (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
print "\n";

So you can use the last one if you want a pure Perl solution, or install Term::ReadKey from CPAN if you want a simpler solution in your code but more up-front set-up.

like image 118
Matt Ryall Avatar answered Oct 13 '22 10:10

Matt Ryall


This obviously depends on the platform, but a very simple solution that works out of the box on Linux is this:

my $width = `tput cols`;
like image 41
roryrjb Avatar answered Oct 13 '22 11:10

roryrjb