我想输出一个进度条,但如何在Perl中获取终端宽度?
最好使用核心的Perl解决方案,因为我没有编译器,只有已经安装好的5.8.2 Perl。
最好使用核心的Perl解决方案,因为我没有编译器,只有已经安装好的5.8.2 Perl。
perldoc -q "screen size"
命令,Perl附带的常见问题解答文档会给出这个问题的答案。
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";
如果您想要一个纯Perl的解决方案,您可以使用最后一个;如果您想在代码中使用更简单的解决方案,但需要更多的前期设置,请从CPAN安装Term::ReadKey。
h2ph
,以解决错误信息:Can't locate sys/ioctl.ph in @INC (did you run h2ph?)
? - Steve Schnepph2ph
时会发生什么? - Etherh2ph
的-d
选项。现在它显示ioctl.pl:ioctl TIOCGWINSZ(40007468:系统调用收到一个无效的参数。)
。 - Steve Schnepp这显然取决于平台,但在Linux上可以直接使用一个非常简单的解决方案:
my $width = `tput cols`;
Term::Size::Any 看起来是你所需要的。