本文介绍了如何在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: $!)\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的:ReadKey .

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中检索终端宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:52