如何在 Perl 中检索终端宽度? [英] How do I retrieve the terminal width in Perl?
问题描述
我想输出一个进度条,但如何在 Perl 中检索终端宽度?
I want to output a progress bar, but how do I retrieve the terminal width in Perl?
首选核心 Perl 解决方案,因为我无法访问编译器,只能使用已安装的 5.8.2 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.
推荐答案
Perl 附带的 FAQ 对这个问题有答案.如果你运行 perldoc -q "screen size"
,你会得到以下内容:
The FAQ which ships with Perl has the answer to this question. If you run perldoc -q "screen size"
, you'll get the following:
如何获取屏幕尺寸?
如果您从 CPAN 安装了 Term::ReadKey
模块,您可以使用它来获取以字符和像素为单位的宽度和高度:
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();
这比原始的ioctl"更具可移植性,但不是说明性的:
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: $!)
", &TIOCGWINSZ;
}
($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);
print "(row,col) = ($row,$col)";
print " (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
print "
";
所以如果你想要一个纯 Perl 解决方案,你可以使用最后一个,或者安装 Term::ReadKey 来自 CPAN,如果您想在代码中使用更简单的解决方案,但需要更多的前期设置.
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.
这篇关于如何在 Perl 中检索终端宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!