ASPN ActiveState Programmer Network
  ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups | Web Services
SEARCH
advanced | search help

Reference
ActivePerl 5.10
Core Documentation
perl
perlintro
perltoc
perlreftut
perldsc
perllol
perlrequick
perlretut
perlboot
perltoot
perltooc
perlbot
perlstyle
perlcheat
perltrap
perldebtut
perlfaq
perlfaq1
perlfaq2
perlfaq3
perlfaq4
perlfaq5
perlfaq6
perlfaq7
perlfaq8
perlfaq9
perlsyn
perldata
perlop
perlsub
perlfunc
perlopentut
perlpacktut
perlpod
perlpodspec
perlrun
perldiag
perllexwarn
perldebug
perlvar
perlre
perlrebackslash
perlrecharclass
perlreref
perlref
perlform
perlobj
perltie
perldbmfilter
perlipc
perlfork
perlnumber
perlthrtut
perlothrtut
perlport
perllocale
perluniintro
perlunicode
perlunifaq
perlunitut
perlebcdic
perlsec
perlmod
perlmodlib
perlmodstyle
perlmodinstall
perlnewmod
perlpragma
perlutil
perlcompile
perlfilter
perlglossary
perlembed
perldebguts
perlxstut
perlxs
perlclib
perlguts
perlcall
perlreapi
perlreguts
perlapi
perlintern
perliol
perlapio
perlhack
perlbook
perlcommunity
perltodo
perldoc
perlhist
perldelta
perl5100delta
perl595delta
perl594delta
perl593delta
perl592delta
perl591delta
perl590delta
perl588delta
perl587delta
perl586delta
perl585delta
perl584delta
perl583delta
perl582delta
perl581delta
perl58delta
perl573delta
perl572delta
perl571delta
perl570delta
perl561delta
perl56delta
perl5005delta
perl5004delta
perlartistic
perlgpl
perlcn
perljp
perlko
perltw
perlaix
perlamiga
perlapollo
perlbeos
perlbs2000
perlce
perlcygwin
perldgux
perldos
perlepoc
perlfreebsd
perlhpux
perlhurd
perlirix
perllinux
perlmachten
perlmacos
perlmacosx
perlmint
perlmpeix
perlnetware
perlopenbsd
perlos2
perlos390
perlos400
perlplan9
perlqnx
perlriscos
perlsolaris
perlsymbian
perltru64
perluts
perlvmesa
perlvms
perlvos
perlwin32

MyASPN >> Reference >> ActivePerl 5.10 >> Core Documentation
ActivePerl 5.10 documentation

perlfaq8 - System Interaction


NAME

perlfaq8 - System Interaction ($Revision: 10183 $)


DESCRIPTION

This section of the Perl FAQ covers questions involving operating system interaction. Topics include interprocess communication (IPC), control over the user-interface (keyboard, screen and pointing devices), and most anything else not related to data manipulation.

Read the FAQs and documentation specific to the port of perl to your operating system (eg, the perlvms manpage, the perlplan9 manpage, ...). These should contain more detailed information on the vagaries of your perl.

How do I find out which operating system I'm running under?

The $^O variable ($OSNAME if you use English) contains an indication of the name of the operating system (not its release number) that your perl binary was built for.

How come exec() doesn't return?

Because that's what it does: it replaces your currently running program with a different one. If you want to keep going (as is probably the case if you're asking this question) use system() instead.

How do I do fancy stuff with the keyboard/screen/mouse?

How you access/control keyboards, screens, and pointing devices ("mice") is system-dependent. Try the following modules:

Keyboard
        Term::Cap               Standard perl distribution
        Term::ReadKey           CPAN
        Term::ReadLine::Gnu     CPAN
        Term::ReadLine::Perl    CPAN
        Term::Screen            CPAN
Screen
        Term::Cap               Standard perl distribution
        Curses                  CPAN
        Term::ANSIColor         CPAN
Mouse
        Tk                      CPAN

Some of these specific cases are shown as examples in other answers in this section of the perlfaq.

How do I print something out in color?

In general, you don't, because you don't know whether the recipient has a color-aware display device. If you know that they have an ANSI terminal that understands color, you can use the Term::ANSIColor module from CPAN:

        use Term::ANSIColor;
        print color("red"), "Stop!\n", color("reset");
        print color("green"), "Go!\n", color("reset");

Or like this:

        use Term::ANSIColor qw(:constants);
        print RED, "Stop!\n", RESET;
        print GREEN, "Go!\n", RESET;

How do I read just one key without waiting for a return key?

Controlling input buffering is a remarkably system-dependent matter. On many systems, you can just use the stty command as shown in getc in the perlfunc manpage, but as you see, that's already getting you into portability snags.

        open(TTY, "+</dev/tty") or die "no tty: $!";
        system "stty  cbreak </dev/tty >/dev/tty 2>&1";
        $key = getc(TTY);               # perhaps this works
        # OR ELSE
        sysread(TTY, $key, 1);  # probably this does
        system "stty -cbreak </dev/tty >/dev/tty 2>&1";

The Term::ReadKey module from CPAN offers an easy-to-use interface that should be more efficient than shelling out to stty for each key. It even includes limited support for Windows.

        use Term::ReadKey;
        ReadMode('cbreak');
        $key = ReadKey(0);
        ReadMode('normal');

However, using the code requires that you have a working C compiler and can use it to build and install a CPAN module. Here's a solution using the standard POSIX module, which is already on your systems (assuming your system supports POSIX).

        use HotKey;
        $key = readkey();

And here's the HotKey module, which hides the somewhat mystifying calls to manipulate the POSIX termios structures.

        # HotKey.pm
        package HotKey;
        @ISA = qw(Exporter);
        @EXPORT = qw(cbreak cooked readkey);
        use strict;
        use POSIX qw(:termios_h);
        my ($term, $oterm, $echo, $noecho, $fd_stdin);
        $fd_stdin = fileno(STDIN);
        $term     = POSIX::Termios->new();
        $term->getattr($fd_stdin);
        $oterm     = $term->getlflag();
        $echo     = ECHO | ECHOK | ICANON;
        $noecho   = $oterm & ~$echo;
        sub cbreak {
                $term->setlflag($noecho);  # ok, so i don't want echo either
                $term->setcc(VTIME, 1);
                $term->setattr($fd_stdin, TCSANOW);
        }
        sub cooked {
                $term->setlflag($oterm);
                $term->setcc(VTIME, 0);
                $term->setattr($fd_stdin, TCSANOW);
        }
        sub readkey {
                my $key = '';
                cbreak();
                sysread(STDIN, $key, 1);
                cooked();
                return $key;
        }
        END { cooked() }
        1;

How do I check whether input is ready on the keyboard?

The easiest way to do this is to read a key in nonblocking mode with the Term::ReadKey module from CPAN, passing it an argument of -1 to indicate not to block:

        use Term::ReadKey;
        ReadMode('cbreak');
        if (defined ($char = ReadKey(-1)) ) {
                # input was waiting and it was $char
        } else {
                # no input was waiting
        }
        ReadMode('normal');                  # restore normal tty settings

How do I clear the screen?

If you only have do so infrequently, use system:

        system("clear");

If you have to do this a lot, save the clear string so you can print it 100 times without calling a program 100 times:

        $clear_string = `clear`;
        print $clear_string;

If you're planning on doing other screen manipulations, like cursor positions, etc, you might wish to use Term::Cap module:

        use Term::Cap;
        $terminal = Term::Cap->Tgetent( {OSPEED => 9600} );
        $clear_string = $terminal->Tputs('cl');

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";

How do I ask the user for a password?

(This question has nothing to do with the web. See a different FAQ for that.)

There's an example of this in crypt in the perlfunc manpage). First, you put the terminal into "no echo" mode, then just read the password normally. You may do this with an old-style ioctl() function, POSIX terminal control (see the POSIX manpage or its documentation the Camel Book), or a call to the stty program, with varying degrees of portability.

You can also do this for most systems using the Term::ReadKey module from CPAN, which is easier to use and in theory more portable.

        use Term::ReadKey;
        ReadMode('noecho');
        $password = ReadLine(0);

How do I read and write the serial port?

This depends on which operating system your program is running on. In the case of Unix, the serial ports will be accessible through files in /dev; on other systems, device names will doubtless differ. Several problem areas common to all device interaction are the fol