tags:

views:

204

answers:

3

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.

+3  A: 

Term::Size::Any looks to be what you're after.

Dan
Not part of core Perl, but still nice to know about
Steve Schnepp
There's a pure-perl version. You shouldn't need a compiler to install it.
Dan
@Dan: Oh... I'll have a look then :-)
Steve Schnepp
+8  A: 

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.

Matt Ryall
How do we run `h2ph` as implied by the error message : `Can't locate sys/ioctl.ph in @INC (did you run h2ph?)`
Steve Schnepp
@Steve: so what happens when you try to run `h2ph`?
Ether
@Ether: i missed the `-d` option of `h2ph`. Now it says `ioctl.pl: ioctl TIOCGWINSZ (40007468: A system call received a parameter that is not valid.)`
Steve Schnepp
+3  A: 

If you want to make a progress bar, don't sweat the details. Use one of the many progress bar modules on CPAN and be done with it.

brian d foy
+1 for an *higher-level* answer. Too bad the Term::ProgressBar needs also Term::ReadKey :-(
Steve Schnepp