How do I retrieve the terminal width in Perl?

后端 未结 4 1004
天命终不由人
天命终不由人 2020-12-03 18:19

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

相关标签:
4条回答
  • 2020-12-03 18:39

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

    0 讨论(0)
  • 2020-12-03 18:45

    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.

    0 讨论(0)
  • 2020-12-03 18:51

    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`;
    
    0 讨论(0)
  • 2020-12-03 18:56

    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.

    0 讨论(0)
提交回复
热议问题