Cari di Perl 
    Perl Tutorial
Daftar Isi
(Sebelumnya) General Perl Language IssuesWeb, Email and Networking (Berikutnya)
FAQs

System Interaction

Daftar Isi

NAME

perlfaq8 - System Interaction

DESCRIPTION

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

Read the FAQs and documentation specific to the port of perl to youroperating system (eg, perlvms, perlplan9, ...). These shouldcontain 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 anindication of the name of the operating system (not its releasenumber) that your perl binary was built for.

How come exec() doesn't return?

(contributed by brian d foy)

The exec function's job is to turn your process into anothercommand and never to return. If that's not what you want to do, don'tuse exec. :)

If you want to run an external command and still keep your Perl processgoing, look at a piped open, fork, or system.

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
    1. Term::Cap Standard perl distribution
    2. Term::ReadKey CPAN
    3. Term::ReadLine::Gnu CPAN
    4. Term::ReadLine::Perl CPAN
    5. Term::Screen CPAN
  • Screen
    1. Term::Cap Standard perl distribution
    2. Curses CPAN
    3. Term::ANSIColor CPAN
  • Mouse
    1. Tk CPAN
    2. Wx CPAN
    3. Gtk2 CPAN
    4. Qt4 kdebindings4 package

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

How do I print something out in color?

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

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

Or like this:

  1. use Term::ANSIColor qw(:constants);
  2. print RED, "Stop!\n", RESET;
  3. 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 ingetc, but as you see, that's already getting you intoportability snags.

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

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

  1. use Term::ReadKey;
  2. ReadMode('cbreak');
  3. $key = ReadKey(0);
  4. ReadMode('normal');

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

  1. use HotKey;
  2. $key = readkey();

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

  1. # HotKey.pm
  2. package HotKey;
  3. use strict;
  4. use warnings;
  5. use parent 'Exporter';
  6. our @EXPORT = qw(cbreak cooked readkey);
  7. use POSIX qw(:termios_h);
  8. my ($term, $oterm, $echo, $noecho, $fd_stdin);
  9. $fd_stdin = fileno(STDIN);
  10. $term = POSIX::Termios->new();
  11. $term->getattr($fd_stdin);
  12. $oterm = $term->getlflag();
  13. $echo = ECHO | ECHOK | ICANON;
  14. $noecho = $oterm & ~$echo;
  15. sub cbreak {
  16. $term->setlflag($noecho); # ok, so i don't want echo either
  17. $term->setcc(VTIME, 1);
  18. $term->setattr($fd_stdin, TCSANOW);
  19. }
  20. sub cooked {
  21. $term->setlflag($oterm);
  22. $term->setcc(VTIME, 0);
  23. $term->setattr($fd_stdin, TCSANOW);
  24. }
  25. sub readkey {
  26. my $key = '';
  27. cbreak();
  28. sysread(STDIN, $key, 1);
  29. cooked();
  30. return $key;
  31. }
  32. END { cooked() }
  33. 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 theTerm::ReadKey module from CPAN, passing it an argument of -1 to indicatenot to block:

  1. use Term::ReadKey;
  2. ReadMode('cbreak');
  3. if (defined (my $char = ReadKey(-1)) ) {
  4. # input was waiting and it was $char
  5. } else {
  6. # no input was waiting
  7. }
  8. ReadMode('normal'); # restore normal tty settings

How do I clear the screen?

(contributed by brian d foy)

To clear the screen, you just have to print the special sequencethat tells the terminal to clear the screen. Once you have thatsequence, output it when you want to clear the screen.

You can use the Term::ANSIScreen module to get the specialsequence. Import the cls function (or the :screen tag):

  1. use Term::ANSIScreen qw(cls);
  2. my $clear_screen = cls();
  3. print $clear_screen;

The Term::Cap module can also get the special sequence if you wantto deal with the low-level details of terminal control. The Tputsmethod returns the string for the given capability:

  1. use Term::Cap;
  2. my $terminal = Term::Cap->Tgetent( { OSPEED => 9600 } );
  3. my $clear_string = $terminal->Tputs('cl');
  4. print $clear_screen;

On Windows, you can use the Win32::Console module. After creatingan object for the output filehandle you want to affect, call theCls method:

  1. Win32::Console;
  2. my $OUT = Win32::Console->new(STD_OUTPUT_HANDLE);
  3. my $clear_string = $OUT->Cls;
  4. print $clear_screen;

If you have a command-line program that does the job, you can callit in backticks to capture whatever it outputs so you can use itlater:

  1. my $clear_string = `clear`;
  2. print $clear_string;

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 charactersand in pixels:

  1. use Term::ReadKey;
  2. my ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();

This is more portable than the raw ioctl, but not asillustrative:

  1. require 'sys/ioctl.ph';
  2. die "no TIOCGWINSZ " unless defined &TIOCGWINSZ;
  3. open(my $tty_fh, "+</dev/tty") or die "No tty: $!";
  4. unless (ioctl($tty_fh, &TIOCGWINSZ, $winsize='')) {
  5. die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\n", &TIOCGWINSZ;
  6. }
  7. my ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);
  8. print "(row,col) = ($row,$col)";
  9. print " (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
  10. print "\n";

How do I ask the user for a password?

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

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

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

  1. use Term::ReadKey;
  2. ReadMode('noecho');
  3. my $password = ReadLine(0);

How do I read and write the serial port?

This depends on which operating system your program is running on. Inthe 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 thefollowing:

  • lockfiles

    Your system may use lockfiles to control multiple access. Make sureyou follow the correct protocol. Unpredictable behavior can resultfrom multiple processes reading from one device.

  • open mode

    If you expect to use both read and write operations on the device,you'll have to open it for update (see open fordetails). You may wish to open it without running the risk ofblocking by using sysopen() and O_RDWR|O_NDELAY|O_NOCTTY from theFcntl module (part of the standard perl distribution). Seesysopen for more on this approach.

  • end of line

    Some devices will be expecting a "\r" at the end of each line ratherthan a "\n". In some ports of perl, "\r" and "\n" are different fromtheir usual (Unix) ASCII values of "\015" and "\012". You may have togive the numeric values you want directly, using octal ("\015"), hex("0x0D"), or as a control-character specification ("\cM").

    1. print DEV "atv1\012"; # wrong, for some devices
    2. print DEV "atv1\015"; # right, for some devices

    Even though with normal text files a "\n" will do the trick, there isstill no unified scheme for terminating a line that is portablebetween Unix, DOS/Win, and Macintosh, except to terminate ALL lineends with "\015\012", and strip what you don't need from the output.This applies especially to socket I/O and autoflushing, discussednext.

  • flushing output

    If you expect characters to get to your device when you print() them,you'll want to autoflush that filehandle. You can use select()and the $| variable to control autoflushing (see perlvar/$and select, or perlfaq5, "How do I flush/unbuffer anoutput filehandle? Why must I do this?"):

    1. my $old_handle = select($dev_fh);
    2. $| = 1;
    3. select($old_handle);

    You'll also see code that does this without a temporary variable, as in

    1. select((select($deb_handle), $| = 1)[0]);

    Or if you don't mind pulling in a few thousand linesof code just because you're afraid of a little $| variable:

    1. use IO::Handle;
    2. $dev_fh->autoflush(1);

    As mentioned in the previous item, this still doesn't work when usingsocket I/O between Unix and Macintosh. You'll need to hard code yourline terminators, in that case.

  • non-blocking input

    If you are doing a blocking read() or sysread(), you'll have toarrange for an alarm handler to provide a timeout (seealarm). If you have a non-blocking open, you'll likelyhave a non-blocking read, which means you may have to use a 4-argselect() to determine whether I/O is ready on that device (seeselect.

While trying to read from his caller-id box, the notorious JamieZawinski <[email protected]>, after much gnashing of teeth andfighting with sysread, sysopen, POSIX's tcgetattr business,and various other functions that go bump in the night, finally came upwith this:

  1. sub open_modem {
  2. use IPC::Open2;
  3. my $stty = `/bin/stty -g`;
  4. open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
  5. # starting cu hoses /dev/tty's stty settings, even when it has
  6. # been opened on a pipe...
  7. system("/bin/stty $stty");
  8. $_ = <MODEM_IN>;
  9. chomp;
  10. if ( !m/^Connected/ ) {
  11. print STDERR "$0: cu printed `$_' instead of `Connected'\n";
  12. }
  13. }

How do I decode encrypted password files?

You spend lots and lots of money on dedicated hardware, but this isbound to get you talked about.

Seriously, you can't if they are Unix password files--the Unixpassword system employs one-way encryption. It's more like hashingthan encryption. The best you can do is check whether something elsehashes to the same string. You can't turn a hash back into theoriginal string. Programs like Crack can forcibly (and intelligently)try to guess passwords, but don't (can't) guarantee quick success.

If you're worried about users selecting bad passwords, you shouldproactively check when they try to change their password (by modifyingpasswd(1), for example).

How do I start a process in the background?

(contributed by brian d foy)

There's not a single way to run code in the background so you don'thave to wait for it to finish before your program moves on to othertasks. Process management depends on your particular operating system,and many of the techniques are covered in perlipc.

Several CPAN modules may be able to help, including IPC::Open2 orIPC::Open3, IPC::Run, Parallel::Jobs,Parallel::ForkManager, POE, Proc::Background, andWin32::Process. There are many other modules you might use, socheck those namespaces for other options too.

If you are on a Unix-like system, you might be able to get away with asystem call where you put an & on the end of the command:

  1. system("cmd &")

You can also try using fork, as described in perlfunc (althoughthis is the same thing that many of the modules will do for you).

  • STDIN, STDOUT, and STDERR are shared

    Both the main process and the backgrounded one (the "child" process)share the same STDIN, STDOUT and STDERR filehandles. If both try toaccess them at once, strange things can happen. You may want to closeor reopen these for the child. You can get around this withopening a pipe (see open) but on some systems thismeans that the child process cannot outlive the parent.

  • Signals

    You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too.SIGCHLD is sent when the backgrounded process finishes. SIGPIPE issent when you write to a filehandle whose child process has closed (anuntrapped SIGPIPE can cause your program to silently die). This isnot an issue with system("cmd&").

  • Zombies

    You have to be prepared to "reap" the child process when it finishes.

    1. $SIG{CHLD} = sub { wait };
    2. $SIG{CHLD} = 'IGNORE';

    You can also use a double fork. You immediately wait() for yourfirst child, and the init daemon will wait() for your grandchild onceit exits.

    1. unless ($pid = fork) {
    2. unless (fork) {
    3. exec "what you really wanna do";
    4. die "exec failed!";
    5. }
    6. exit 0;
    7. }
    8. waitpid($pid, 0);

    See Signals in perlipc for other examples of code to do this.Zombies are not an issue with system("prog &").

How do I trap control characters/signals?

You don't actually "trap" a control character. Instead, that charactergenerates a signal which is sent to your terminal's currentlyforegrounded process group, which you then trap in your process.Signals are documented in Signals in perlipc and thesection on "Signals" in the Camel.

You can set the values of the %SIG hash to be the functions you wantto handle the signal. After perl catches the signal, it looks in %SIGfor a key with the same name as the signal, then calls the subroutinevalue for that key.

  1. # as an anonymous subroutine
  2. $SIG{INT} = sub { syswrite(STDERR, "ouch\n", 5 ) };
  3. # or a reference to a function
  4. $SIG{INT} = \&ouch;
  5. # or the name of the function as a string
  6. $SIG{INT} = "ouch";

Perl versions before 5.8 had in its C source code signal handlers whichwould catch the signal and possibly run a Perl function that you had setin %SIG. This violated the rules of signal handling at that levelcausing perl to dump core. Since version 5.8.0, perl looks at %SIGafter the signal has been caught, rather than while it is being caught.Previous versions of this answer were incorrect.

How do I modify the shadow password file on a Unix system?

If perl was installed correctly and your shadow library was writtenproperly, the getpw*() functions described in perlfunc should intheory provide (read-only) access to entries in the shadow passwordfile. To change the file, make a new shadow password file (the formatvaries from system to system--see passwd(1) for specifics) and usepwd_mkdb(8) to install it (see pwd_mkdb(8) for more details).

How do I set the time and date?

Assuming you're running under sufficient permissions, you should beable to set the system-wide date and time by running the date(1)program. (There is no way to set the time and date on a per-processbasis.) This mechanism will work for Unix, MS-DOS, Windows, and NT;the VMS equivalent is set time.

However, if all you want to do is change your time zone, you canprobably get away with setting an environment variable:

  1. $ENV{TZ} = "MST7MDT"; # Unixish
  2. $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
  3. system('trn', 'comp.lang.perl.misc');

How can I sleep() or alarm() for under a second?

If you want finer granularity than the 1 second that the sleep()function provides, the easiest way is to use the select() function asdocumented in select. Try the Time::HiRes andthe BSD::Itimer modules (available from CPAN, and starting fromPerl 5.8 Time::HiRes is part of the standard distribution).

How can I measure time under a second?

(contributed by brian d foy)

The Time::HiRes module (part of the standard distribution as ofPerl 5.8) measures time with the gettimeofday() system call, whichreturns the time in microseconds since the epoch. If you can't installTime::HiRes for older Perls and you are on a Unixish system, youmay be able to call gettimeofday(2) directly. Seesyscall.

How can I do an atexit() or setjmp()/longjmp()? (Exception handling)

You can use the END block to simulate atexit(). Each package'sEND block is called when the program or thread ends. See the perlmodmanpage for more details about END blocks.

For example, you can use this to make sure your filter program managedto finish its output without filling up the disk:

  1. END {
  2. close(STDOUT) || die "stdout close failed: $!";
  3. }

The END block isn't called when untrapped signals kill the program,though, so if you use END blocks you should also use

  1. use sigtrap qw(die normal-signals);

Perl's exception-handling mechanism is its eval() operator. Youcan use eval() as setjmp and die() as longjmp. Fordetails of this, see the section on signals, especially the time-outhandler for a blocking flock() in Signals in perlipc or thesection on "Signals" in Programming Perl.

If exception handling is all you're interested in, use one of themany CPAN modules that handle exceptions, such as Try::Tiny.

If you want the atexit() syntax (and an rmexit() as well), try theAtExit module available from CPAN.

Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean?

Some Sys-V based systems, notably Solaris 2.X, redefined some of thestandard socket constants. Since these were constant across allarchitectures, they were often hardwired into perl code. The properway to deal with this is to "use Socket" to get the correct values.

Note that even though SunOS and Solaris are binary compatible, thesevalues are different. Go figure.

How can I call my system's unique C functions from Perl?

In most cases, you write an external module to do it--see the answerto "Where can I learn about linking C with Perl? [h2xs, xsubpp]".However, if the function is a system call, and your system supportssyscall(), you can use the syscall function (documented inperlfunc).

Remember to check the modules that came with your distribution, andCPAN as well--someone may already have written a module to do it. OnWindows, try Win32::API. On Macs, try Mac::Carbon. If no modulehas an interface to the C function, you can inline a bit of C in yourPerl source with Inline::C.

Where do I get the include files to do ioctl() or syscall()?

Historically, these would be generated by the h2ph tool, part of thestandard perl distribution. This program converts cpp(1) directivesin C header files to files containing subroutine definitions, like&SYS_getitimer, which you can use as arguments to your functions.It doesn't work perfectly, but it usually gets most of the job done.Simple files like errno.h, syscall.h, and socket.h were fine,but the hard ones like ioctl.h nearly always need to be hand-edited.Here's how to install the *.ph files:

  1. 1. Become the super-user
  2. 2. cd /usr/include
  3. 3. h2ph *.h */*.h

If your system supports dynamic loading, for reasons of portability andsanity you probably ought to use h2xs (also part of the standard perldistribution). This tool converts C header files to Perl extensions.See perlxstut for how to get started with h2xs.

If your system doesn't support dynamic loading, you still probablyought to use h2xs. See perlxstut and ExtUtils::MakeMaker formore information (in brief, just use make perl instead of a plainmake to rebuild perl with a new static extension).

Why do setuid perl scripts complain about kernel problems?

Some operating systems have bugs in the kernel that make setuidscripts inherently insecure. Perl gives you a number of options(described in perlsec) to work around such systems.

How can I open a pipe both to and from a command?

The IPC::Open2 module (part of the standard perl distribution) isan easy-to-use approach that internally uses pipe(), fork(), andexec() to do the job. Make sure you read the deadlock warnings inits documentation, though (see IPC::Open2). SeeBidirectional Communication with Another Process in perlipc andBidirectional Communication with Yourself in perlipc

You may also use the IPC::Open3 module (part of the standard perldistribution), but be warned that it has a different order ofarguments from IPC::Open2 (see IPC::Open3).

Why can't I get the output of a command with system()?

You're confusing the purpose of system() and backticks (``). system()runs a command and returns exit status information (as a 16 bit value:the low 7 bits are the signal the process died from, if any, andthe high 8 bits are the actual exit value). Backticks (``) run acommand and return what it sent to STDOUT.

  1. my $exit_status = system("mail-users");
  2. my $output_string = `ls`;

How can I capture STDERR from an external command?

There are three basic ways of running external commands:

  1. system $cmd; # using system()
  2. my $output = `$cmd`; # using backticks (``)
  3. open (my $pipe_fh, "$cmd |"); # using open()

With system(), both STDOUT and STDERR will go the same place as thescript's STDOUT and STDERR, unless the system() command redirects them.Backticks and open() read only the STDOUT of your command.

You can also use the open3() function from IPC::Open3. BenjaminGoldberg provides some sample code:

To capture a program's STDOUT, but discard its STDERR:

  1. use IPC::Open3;
  2. use File::Spec;
  3. use Symbol qw(gensym);
  4. open(NULL, ">", File::Spec->devnull);
  5. my $pid = open3(gensym, \*PH, ">&NULL", "cmd");
  6. while( <PH> ) { }
  7. waitpid($pid, 0);

To capture a program's STDERR, but discard its STDOUT:

  1. use IPC::Open3;
  2. use File::Spec;
  3. use Symbol qw(gensym);
  4. open(NULL, ">", File::Spec->devnull);
  5. my $pid = open3(gensym, ">&NULL", \*PH, "cmd");
  6. while( <PH> ) { }
  7. waitpid($pid, 0);

To capture a program's STDERR, and let its STDOUT go to our own STDERR:

  1. use IPC::Open3;
  2. use Symbol qw(gensym);
  3. my $pid = open3(gensym, ">&STDERR", \*PH, "cmd");
  4. while( <PH> ) { }
  5. waitpid($pid, 0);

To read both a command's STDOUT and its STDERR separately, you canredirect them to temp files, let the command run, then read the tempfiles:

  1. use IPC::Open3;
  2. use Symbol qw(gensym);
  3. use IO::File;
  4. local *CATCHOUT = IO::File->new_tmpfile;
  5. local *CATCHERR = IO::File->new_tmpfile;
  6. my $pid = open3(gensym, ">&CATCHOUT", ">&CATCHERR", "cmd");
  7. waitpid($pid, 0);
  8. seek $_, 0, 0 for \*CATCHOUT, \*CATCHERR;
  9. while( <CATCHOUT> ) {}
  10. while( <CATCHERR> ) {}

But there's no real need for both to be tempfiles... the followingshould work just as well, without deadlocking:

  1. use IPC::Open3;
  2. use Symbol qw(gensym);
  3. use IO::File;
  4. local *CATCHERR = IO::File->new_tmpfile;
  5. my $pid = open3(gensym, \*CATCHOUT, ">&CATCHERR", "cmd");
  6. while( <CATCHOUT> ) {}
  7. waitpid($pid, 0);
  8. seek CATCHERR, 0, 0;
  9. while( <CATCHERR> ) {}

And it'll be faster, too, since we can begin processing the program'sstdout immediately, rather than waiting for the program to finish.

With any of these, you can change file descriptors before the call:

  1. open(STDOUT, ">logfile");
  2. system("ls");

or you can use Bourne shell file-descriptor redirection:

  1. $output = `$cmd 2>some_file`;
  2. open (PIPE, "cmd 2>some_file |");

You can also use file-descriptor redirection to make STDERR aduplicate of STDOUT:

  1. $output = `$cmd 2>&1`;
  2. open (PIPE, "cmd 2>&1 |");

Note that you cannot simply open STDERR to be a dup of STDOUTin your Perl program and avoid calling the shell to do the redirection.This doesn't work:

  1. open(STDERR, ">&STDOUT");
  2. $alloutput = `cmd args`; # stderr still escapes

This fails because the open() makes STDERR go to where STDOUT wasgoing at the time of the open(). The backticks then make STDOUT go toa string, but don't change STDERR (which still goes to the oldSTDOUT).

Note that you must use Bourne shell (sh(1)) redirection syntax inbackticks, not csh(1)! Details on why Perl's system() and backtickand pipe opens all use the Bourne shell are in theversus/csh.whynot article in the "Far More Than You Ever Wanted ToKnow" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz . Tocapture a command's STDERR and STDOUT together:

  1. $output = `cmd 2>&1`; # either with backticks
  2. $pid = open(PH, "cmd 2>&1 |"); # or with an open pipe
  3. while (<PH>) { } # plus a read

To capture a command's STDOUT but discard its STDERR:

  1. $output = `cmd 2>/dev/null`; # either with backticks
  2. $pid = open(PH, "cmd 2>/dev/null |"); # or with an open pipe
  3. while (<PH>) { } # plus a read

To capture a command's STDERR but discard its STDOUT:

  1. $output = `cmd 2>&1 1>/dev/null`; # either with backticks
  2. $pid = open(PH, "cmd 2>&1 1>/dev/null |"); # or with an open pipe
  3. while (<PH>) { } # plus a read

To exchange a command's STDOUT and STDERR in order to capture the STDERRbut leave its STDOUT to come out our old STDERR:

  1. $output = `cmd 3>&1 1>&2 2>&3 3>&-`; # either with backticks
  2. $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
  3. while (<PH>) { } # plus a read

To read both a command's STDOUT and its STDERR separately, it's easiestto redirect them separately to files, and then read from those fileswhen the program is done:

  1. system("program args 1>program.stdout 2>program.stderr");

Ordering is important in all these examples. That's because the shellprocesses file descriptor redirections in strictly left to right order.

  1. system("prog args 1>tmpfile 2>&1");
  2. system("prog args 2>&1 1>tmpfile");

The first command sends both standard out and standard error to thetemporary file. The second command sends only the old standard outputthere, and the old standard error shows up on the old standard out.

Why doesn't open() return an error when a pipe open fails?

If the second argument to a piped open() contains shellmetacharacters, perl fork()s, then exec()s a shell to decode themetacharacters and eventually run the desired program. If the programcouldn't be run, it's the shell that gets the message, not Perl. Allyour Perl program can find out is whether the shell itself could besuccessfully started. You can still capture the shell's STDERR andcheck it for error messages. See How can I capture STDERR from an external command? elsewhere in this document, or use theIPC::Open3 module.

If there are no shell metacharacters in the argument of open(), Perlruns the command directly, without using the shell, and can correctlyreport whether the command started.

What's wrong with using backticks in a void context?

Strictly speaking, nothing. Stylistically speaking, it's not a goodway to write maintainable code. Perl has several operators forrunning external commands. Backticks are one; they collect the outputfrom the command for use in your program. The system function isanother; it doesn't do this.

Writing backticks in your program sends a clear message to the readersof your code that you wanted to collect the output of the command.Why send a clear message that isn't true?

Consider this line:

  1. `cat /etc/termcap`;

You forgot to check $? to see whether the program even rancorrectly. Even if you wrote

  1. print `cat /etc/termcap`;

this code could and probably should be written as

  1. system("cat /etc/termcap") == 0
  2. or die "cat program failed!";

which will echo the cat command's output as it is generated, insteadof waiting until the program has completed to print it out. It alsochecks the return value.

system also provides direct control over whether shell wildcardprocessing may take place, whereas backticks do not.

How can I call backticks without shell processing?

This is a bit tricky. You can't simply write the commandlike this:

  1. @ok = `grep @opts '$search_string' @filenames`;

As of Perl 5.8.0, you can use open() with multiple arguments.Just like the list forms of system() and exec(), no shellescapes happen.

  1. open( GREP, "-|", 'grep', @opts, $search_string, @filenames );
  2. chomp(@ok = <GREP>);
  3. close GREP;

You can also:

  1. my @ok = ();
  2. if (open(GREP, "-|")) {
  3. while (<GREP>) {
  4. chomp;
  5. push(@ok, $_);
  6. }
  7. close GREP;
  8. } else {
  9. exec 'grep', @opts, $search_string, @filenames;
  10. }

Just as with system(), no shell escapes happen when you exec() alist. Further examples of this can be found in Safe Pipe Opens in perlipc.

Note that if you're using Windows, no solution to this vexing issue iseven possible. Even though Perl emulates fork(), you'll still bestuck, because Windows does not have an argc/argv-style API.

Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?

This happens only if your perl is compiled to use stdio instead ofperlio, which is the default. Some (maybe all?) stdios set error andeof flags that you may need to clear. The POSIX module definesclearerr() that you can use. That is the technically correct way todo it. Here are some less reliable workarounds:

1

Try keeping around the seekpointer and go there, like this:

  1. my $where = tell($log_fh);
  2. seek($log_fh, $where, 0);
2

If that doesn't work, try seeking to a different part of the file andthen back.

3

If that doesn't work, try seeking to a different part ofthe file, reading something, and then seeking back.

4

If that doesn't work, give up on your stdio package and use sysread.

How can I convert my shell script to perl?

Learn Perl and rewrite it. Seriously, there's no simple converter.Things that are awkward to do in the shell are easy to do in Perl, andthis very awkwardness is what would make a shell->perl converternigh-on impossible to write. By rewriting it, you'll think about whatyou're really trying to do, and hopefully will escape the shell'spipeline datastream paradigm, which while convenient for some matters,causes many inefficiencies.

Can I use perl to run a telnet or ftp session?

Try the Net::FTP, TCP::Client, and Net::Telnet modules(available from CPAN).http://www.cpan.org/scripts/netstuff/telnet.emul.shar will also helpfor emulating the telnet protocol, but Net::Telnet is quiteprobably easier to use.

If all you want to do is pretend to be telnet but don't needthe initial telnet handshaking, then the standard dual-processapproach will suffice:

  1. use IO::Socket; # new in 5.004
  2. my $handle = IO::Socket::INET->new('www.perl.com:80')
  3. or die "can't connect to port 80 on www.perl.com $!";
  4. $handle->autoflush(1);
  5. if (fork()) { # XXX: undef means failure
  6. select($handle);
  7. print while <STDIN>; # everything from stdin to socket
  8. } else {
  9. print while <$handle>; # everything from socket to stdout
  10. }
  11. close $handle;
  12. exit;

How can I write expect in Perl?

Once upon a time, there was a library called chat2.pl (part of thestandard perl distribution), which never really got finished. If youfind it somewhere, don't use it. These days, your best bet is tolook at the Expect module available from CPAN, which also requires twoother modules from CPAN, IO::Pty and IO::Stty.

Is there a way to hide perl's command line from programs such as "ps"?

First of all note that if you're doing this for security reasons (toavoid people seeing passwords, for example) then you should rewriteyour program so that critical information is never given as anargument. Hiding the arguments won't make your program completelysecure.

To actually alter the visible command line, you can assign to thevariable $0 as documented in perlvar. This won't work on alloperating systems, though. Daemon programs like sendmail place theirstate there, as in:

  1. $0 = "orcus [accepting connections]";

I {changed directory, modified my environment} in a perl script. How come the change disappeared when I exited the script? How do I get my changes to be visible?

  • Unix

    In the strictest sense, it can't be done--the script executes as adifferent process from the shell it was started from. Changes to aprocess are not reflected in its parent--only in any childrencreated after the change. There is shell magic that may allow you tofake it by eval()ing the script's output in your shell; check out thecomp.unix.questions FAQ for details.

How do I close a process's filehandle without waiting for it to complete?

Assuming your system supports such things, just send an appropriate signalto the process (see kill). It's common to first send a TERMsignal, wait a little bit, and then send a KILL signal to finish it off.

How do I fork a daemon process?

If by daemon process you mean one that's detached (disassociated fromits tty), then the following process is reported to work on mostUnixish systems. Non-Unix users should check their Your_OS::Processmodule for other solutions.

  • Open /dev/tty and use the TIOCNOTTY ioctl on it. See tty(1)for details. Or better yet, you can just use the POSIX::setsid()function, so you don't have to worry about process groups.

  • Change directory to /

  • Reopen STDIN, STDOUT, and STDERR so they're not connected to the oldtty.

  • Background yourself like this:

    1. fork && exit;

The Proc::Daemon module, available from CPAN, provides a function toperform these actions for you.

How do I find out if I'm running interactively or not?

(contributed by brian d foy)

This is a difficult question to answer, and the best answer isonly a guess.

What do you really want to know? If you merely want to know if one ofyour filehandles is connected to a terminal, you can try the -tfile test:

  1. if( -t STDOUT ) {
  2. print "I'm connected to a terminal!\n";
  3. }

However, you might be out of luck if you expect that means there is areal person on the other side. With the Expect module, anotherprogram can pretend to be a person. The program might even come closeto passing the Turing test.

The IO::Interactive module does the best it can to give you ananswer. Its is_interactive function returns an output filehandle;that filehandle points to standard output if the module thinks thesession is interactive. Otherwise, the filehandle is a null handlethat simply discards the output:

  1. use IO::Interactive;
  2. print { is_interactive } "I might go to standard output!\n";

This still doesn't guarantee that a real person is answering yourprompts or reading your output.

If you want to know how to handle automated testing for yourdistribution, you can check the environment. The CPANTesters, for instance, set the value of AUTOMATED_TESTING:

  1. unless( $ENV{AUTOMATED_TESTING} ) {
  2. print "Hello interactive tester!\n";
  3. }

How do I timeout a slow event?

Use the alarm() function, probably in conjunction with a signalhandler, as documented in Signals in perlipc and the section on"Signals" in the Camel. You may instead use the more flexibleSys::AlarmCall module available from CPAN.

The alarm() function is not implemented on all versions of Windows.Check the documentation for your specific version of Perl.

How do I set CPU limits?

(contributed by Xho)

Use the BSD::Resource module from CPAN. As an example:

  1. use BSD::Resource;
  2. setrlimit(RLIMIT_CPU,10,20) or die $!;

This sets the soft and hard limits to 10 and 20 seconds, respectively.After 10 seconds of time spent running on the CPU (not "wall" time),the process will be sent a signal (XCPU on some systems) which, if nottrapped, will cause the process to terminate. If that signal istrapped, then after 10 more seconds (20 seconds in total) the processwill be killed with a non-trappable signal.

See the BSD::Resource and your systems documentation for the gorydetails.

How do I avoid zombies on a Unix system?

Use the reaper code from Signals in perlipc to call wait() when aSIGCHLD is received, or else use the double-fork technique describedin How do I start a process in the background? in perlfaq8.

How do I use an SQL database?

The DBI module provides an abstract interface to most databaseservers and types, including Oracle, DB2, Sybase, mysql, Postgresql,ODBC, and flat files. The DBI module accesses each database typethrough a database driver, or DBD. You can see a complete list ofavailable drivers on CPAN: http://www.cpan.org/modules/by-module/DBD/ .You can read more about DBI on http://dbi.perl.org/ .

Other modules provide more specific access: Win32::ODBC, Alzabo,iodbc, and others found on CPAN Search: http://search.cpan.org/ .

How do I make a system() exit on control-C?

You can't. You need to imitate the system() call (see perlipc forsample code) and then have a signal handler for the INT signal thatpasses the signal on to the subprocess. Or you can check for it:

  1. $rc = system($cmd);
  2. if ($rc & 127) { die "signal death" }

How do I open a file without blocking?

If you're lucky enough to be using a system that supportsnon-blocking reads (most Unixish systems do), you need only to use theO_NDELAY or O_NONBLOCK flag from the Fcntl module in conjunction withsysopen():

  1. use Fcntl;
  2. sysopen(my $fh, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)
  3. or die "can't open /foo/somefile: $!":

How do I tell the difference between errors from the shell and perl?

(answer contributed by brian d foy)

When you run a Perl script, something else is running the script for you,and that something else may output error messages. The script mightemit its own warnings and error messages. Most of the time you cannottell who said what.

You probably cannot fix the thing that runs perl, but you can change howperl outputs its warnings by defining a custom warning and die functions.

Consider this script, which has an error you may not notice immediately.

  1. #!/usr/locl/bin/perl
  2. print "Hello World\n";

I get an error when I run this from my shell (which happens to bebash). That may look like perl forgot it has a print() function,but my shebang line is not the path to perl, so the shell runs thescript, and I get the error.

  1. $ ./test
  2. ./test: line 3: print: command not found

A quick and dirty fix involves a little bit of code, but this may be allyou need to figure out the problem.

  1. #!/usr/bin/perl -w
  2. BEGIN {
  3. $SIG{__WARN__} = sub{ print STDERR "Perl: ", @_; };
  4. $SIG{__DIE__} = sub{ print STDERR "Perl: ", @_; exit 1};
  5. }
  6. $a = 1 + undef;
  7. $x / 0;
  8. __END__

The perl message comes out with "Perl" in front. The BEGIN blockworks at compile time so all of the compilation errors and warningsget the "Perl:" prefix too.

  1. Perl: Useless use of division (/) in void context at ./test line 9.
  2. Perl: Name "main::a" used only once: possible typo at ./test line 8.
  3. Perl: Name "main::x" used only once: possible typo at ./test line 9.
  4. Perl: Use of uninitialized value in addition (+) at ./test line 8.
  5. Perl: Use of uninitialized value in division (/) at ./test line 9.
  6. Perl: Illegal division by zero at ./test line 9.
  7. Perl: Illegal division by zero at -e line 3.

If I don't see that "Perl:", it's not from perl.

You could also just know all the perl errors, and although there aresome people who may know all of them, you probably don't. However, theyall should be in the perldiag manpage. If you don't find the error inthere, it probably isn't a perl error.

Looking up every message is not the easiest way, so let perl to do itfor you. Use the diagnostics pragma with turns perl's normal messagesinto longer discussions on the topic.

  1. use diagnostics;

If you don't get a paragraph or two of expanded discussion, itmight not be perl's message.

How do I install a module from CPAN?

(contributed by brian d foy)

The easiest way is to have a module also named CPAN do it for you by usingthe cpan command that comes with Perl. You can give it a list of modulesto install:

  1. $ cpan IO::Interactive Getopt::Whatever

If you prefer CPANPLUS, it's just as easy:

  1. $ cpanp i IO::Interactive Getopt::Whatever

If you want to install a distribution from the current directory, you cantell CPAN.pm to install . (the full stop):

  1. $ cpan .

See the documentation for either of those commands to see what elseyou can do.

If you want to try to install a distribution by yourself, resolvingall dependencies on your own, you follow one of two possible buildpaths.

For distributions that use Makefile.PL:

  1. $ perl Makefile.PL
  2. $ make test install

For distributions that use Build.PL:

  1. $ perl Build.PL
  2. $ ./Build test
  3. $ ./Build install

Some distributions may need to link to libraries or other third-partycode and their build and installation sequences may be more complicated.Check any README or INSTALL files that you may find.

What's the difference between require and use?

(contributed by brian d foy)

Perl runs require statement at run-time. Once Perl loads, compiles,and runs the file, it doesn't do anything else. The use statementis the same as a require run at compile-time, but Perl also calls theimport method for the loaded package. These two are the same:

  1. use MODULE qw(import list);
  2. BEGIN {
  3. require MODULE;
  4. MODULE->import(import list);
  5. }

However, you can suppress the import by using an explicit, emptyimport list. Both of these still happen at compile-time:

  1. use MODULE ();
  2. BEGIN {
  3. require MODULE;
  4. }

Since use will also call the import method, the actual valuefor MODULE must be a bareword. That is, use cannot load filesby name, although require can:

  1. require "$ENV{HOME}/lib/Foo.pm"; # no @INC searching!

See the entry for use in perlfunc for more details.

How do I keep my own module/library directory?

When you build modules, tell Perl where to install the modules.

If you want to install modules for your own use, the easiest way mightbe local::lib, which you can download from CPAN. It sets variousinstallation settings for you, and uses those same settings withinyour programs.

If you want more flexibility, you need to configure your CPAN clientfor your particular situation.

For Makefile.PL-based distributions, use the INSTALL_BASE optionwhen generating Makefiles:

  1. perl Makefile.PL INSTALL_BASE=/mydir/perl

You can set this in your CPAN.pm configuration so modulesautomatically install in your private library directory when you usethe CPAN.pm shell:

  1. % cpan
  2. cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
  3. cpan> o conf commit

For Build.PL-based distributions, use the --install_base option:

  1. perl Build.PL --install_base /mydir/perl

You can configure CPAN.pm to automatically use this option too:

  1. % cpan
  2. cpan> o conf mbuild_arg "--install_base /mydir/perl"
  3. cpan> o conf commit

INSTALL_BASE tells these tools to put your modules into/mydir/perl/lib/perl5. See How do I add a directory to my include path (@INC) at runtime? for details on how to run your newlyinstalled modules.

There is one caveat with INSTALL_BASE, though, since it actsdifferently from the PREFIX and LIB settings that older versions ofExtUtils::MakeMaker advocated. INSTALL_BASE does not supportinstalling modules for multiple versions of Perl or differentarchitectures under the same directory. You should consider whether youreally want that and, if you do, use the older PREFIX and LIBsettings. See the ExtUtils::Makemaker documentation for more details.

How do I add the directory my program lives in to the module/library search path?

(contributed by brian d foy)

If you know the directory already, you can add it to @INC as you wouldfor any other directory. You might <use lib> if you know the directoryat compile time:

  1. use lib $directory;

The trick in this task is to find the directory. Before your script doesanything else (such as a chdir), you can get the current workingdirectory with the Cwd module, which comes with Perl:

  1. BEGIN {
  2. use Cwd;
  3. our $directory = cwd;
  4. }
  5. use lib $directory;

You can do a similar thing with the value of $0, which holds thescript name. That might hold a relative path, but rel2abs can turnit into an absolute path. Once you have the

  1. BEGIN {
  2. use File::Spec::Functions qw(rel2abs);
  3. use File::Basename qw(dirname);
  4. my $path = rel2abs( $0 );
  5. our $directory = dirname( $path );
  6. }
  7. use lib $directory;

The FindBin module, which comes with Perl, might work. It finds thedirectory of the currently running script and puts it in $Bin, whichyou can then use to construct the right library path:

  1. use FindBin qw($Bin);

You can also use local::lib to do much of the same thing. Installmodules using local::lib's settings then use the module in yourprogram:

  1. use local::lib; # sets up a local lib at ~/perl5

See the local::lib documentation for more details.

How do I add a directory to my include path (@INC) at runtime?

Here are the suggested ways of modifying your include path, includingenvironment variables, run-time switches, and in-code statements:

  • the PERLLIB environment variable
    1. $ export PERLLIB=/path/to/my/dir
    2. $ perl program.pl
  • the PERL5LIB environment variable
    1. $ export PERL5LIB=/path/to/my/dir
    2. $ perl program.pl
  • the perl -Idir command line flag
    1. $ perl -I/path/to/my/dir program.pl
  • the lib pragma:
    1. use lib "$ENV{HOME}/myown_perllib";
  • the local::lib module:
    1. use local::lib;
    2. use local::lib "~/myown_perllib";

The last is particularly useful because it knows about machine-dependentarchitectures. The lib.pm pragmatic module was firstincluded with the 5.002 release of Perl.

What is socket.ph and where do I get it?

It's a Perl 4 style file defining values for system networkingconstants. Sometimes it is built using h2ph when Perl is installed,but other times it is not. Modern programs should use use Socket;instead.

AUTHOR AND COPYRIGHT

Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, andother authors as noted. All rights reserved.

This documentation is free; you can redistribute it and/or modify itunder the same terms as Perl itself.

Irrespective of its distribution, all code examples in this fileare hereby placed into the public domain. You are permitted andencouraged to use this code in your own programs for funor for profit as you see fit. A simple comment in the code givingcredit would be courteous but is not required.

Page index
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) General Perl Language IssuesWeb, Email and Networking (Berikutnya)