3 perlfaq8 - System Interaction
7 This section of the Perl FAQ covers questions involving operating
8 system interaction. Topics include interprocess communication (IPC),
9 control over the user-interface (keyboard, screen and pointing
10 devices), and most anything else not related to data manipulation.
12 Read the FAQs and documentation specific to the port of perl to your
13 operating system (eg, L<perlvms>, L<perlplan9>, ...). These should
14 contain more detailed information on the vagaries of your perl.
16 =head2 How do I find out which operating system I'm running under?
18 The C<$^O> variable (C<$OSNAME> if you use C<English>) contains an
19 indication of the name of the operating system (not its release
20 number) that your perl binary was built for.
22 =head2 How come exec() doesn't return?
23 X<exec> X<system> X<fork> X<open> X<pipe>
25 (contributed by brian d foy)
27 The C<exec> function's job is to turn your process into another
28 command and never to return. If that's not what you want to do, don't
31 If you want to run an external command and still keep your Perl process
32 going, look at a piped C<open>, C<fork>, or C<system>.
34 =head2 How do I do fancy stuff with the keyboard/screen/mouse?
36 How you access/control keyboards, screens, and pointing devices
37 ("mice") is system-dependent. Try the following modules:
43 Term::Cap Standard perl distribution
45 Term::ReadLine::Gnu CPAN
46 Term::ReadLine::Perl CPAN
51 Term::Cap Standard perl distribution
61 Some of these specific cases are shown as examples in other answers
62 in this section of the perlfaq.
64 =head2 How do I print something out in color?
66 In general, you don't, because you don't know whether
67 the recipient has a color-aware display device. If you
68 know that they have an ANSI terminal that understands
69 color, you can use the C<Term::ANSIColor> module from CPAN:
72 print color("red"), "Stop!\n", color("reset");
73 print color("green"), "Go!\n", color("reset");
77 use Term::ANSIColor qw(:constants);
78 print RED, "Stop!\n", RESET;
79 print GREEN, "Go!\n", RESET;
81 =head2 How do I read just one key without waiting for a return key?
83 Controlling input buffering is a remarkably system-dependent matter.
84 On many systems, you can just use the B<stty> command as shown in
85 L<perlfunc/getc>, but as you see, that's already getting you into
88 open(TTY, "+</dev/tty") or die "no tty: $!";
89 system "stty cbreak </dev/tty >/dev/tty 2>&1";
90 $key = getc(TTY); # perhaps this works
92 sysread(TTY, $key, 1); # probably this does
93 system "stty -cbreak </dev/tty >/dev/tty 2>&1";
95 The C<Term::ReadKey> module from CPAN offers an easy-to-use interface that
96 should be more efficient than shelling out to B<stty> for each key.
97 It even includes limited support for Windows.
104 However, using the code requires that you have a working C compiler
105 and can use it to build and install a CPAN module. Here's a solution
106 using the standard C<POSIX> module, which is already on your system
107 (assuming your system supports POSIX).
112 And here's the C<HotKey> module, which hides the somewhat mystifying calls
113 to manipulate the POSIX termios structures.
119 @EXPORT = qw(cbreak cooked readkey);
122 use POSIX qw(:termios_h);
123 my ($term, $oterm, $echo, $noecho, $fd_stdin);
125 $fd_stdin = fileno(STDIN);
126 $term = POSIX::Termios->new();
127 $term->getattr($fd_stdin);
128 $oterm = $term->getlflag();
130 $echo = ECHO | ECHOK | ICANON;
131 $noecho = $oterm & ~$echo;
134 $term->setlflag($noecho); # ok, so i don't want echo either
135 $term->setcc(VTIME, 1);
136 $term->setattr($fd_stdin, TCSANOW);
140 $term->setlflag($oterm);
141 $term->setcc(VTIME, 0);
142 $term->setattr($fd_stdin, TCSANOW);
148 sysread(STDIN, $key, 1);
157 =head2 How do I check whether input is ready on the keyboard?
159 The easiest way to do this is to read a key in nonblocking mode with the
160 C<Term::ReadKey> module from CPAN, passing it an argument of -1 to indicate
167 if (defined ($char = ReadKey(-1)) ) {
168 # input was waiting and it was $char
170 # no input was waiting
173 ReadMode('normal'); # restore normal tty settings
175 =head2 How do I clear the screen?
177 (contributed by brian d foy)
179 To clear the screen, you just have to print the special sequence
180 that tells the terminal to clear the screen. Once you have that
181 sequence, output it when you want to clear the screen.
183 You can use the C<Term::ANSIScreen> module to get the special
184 sequence. Import the C<cls> function (or the C<:screen> tag):
186 use Term::ANSIScreen qw(cls);
187 my $clear_screen = cls();
191 The C<Term::Cap> module can also get the special sequence if you want
192 to deal with the low-level details of terminal control. The C<Tputs>
193 method returns the string for the given capability:
197 $terminal = Term::Cap->Tgetent( { OSPEED => 9600 } );
198 $clear_string = $terminal->Tputs('cl');
202 On Windows, you can use the C<Win32::Console> module. After creating
203 an object for the output filehandle you want to affect, call the
208 $OUT = Win32::Console->new(STD_OUTPUT_HANDLE);
209 my $clear_string = $OUT->Cls;
213 If you have a command-line program that does the job, you can call
214 it in backticks to capture whatever it outputs so you can use it
217 $clear_string = `clear`;
221 =head2 How do I get the screen size?
223 If you have C<Term::ReadKey> module installed from CPAN,
224 you can use it to fetch the width and height in characters
228 ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
230 This is more portable than the raw C<ioctl>, but not as
233 require 'sys/ioctl.ph';
234 die "no TIOCGWINSZ " unless defined &TIOCGWINSZ;
235 open(TTY, "+</dev/tty") or die "No tty: $!";
236 unless (ioctl(TTY, &TIOCGWINSZ, $winsize='')) {
237 die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\n", &TIOCGWINSZ;
239 ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);
240 print "(row,col) = ($row,$col)";
241 print " (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
244 =head2 How do I ask the user for a password?
246 (This question has nothing to do with the web. See a different
249 There's an example of this in L<perlfunc/crypt>). First, you put the
250 terminal into "no echo" mode, then just read the password normally.
251 You may do this with an old-style C<ioctl()> function, POSIX terminal
252 control (see L<POSIX> or its documentation the Camel Book), or a call
253 to the B<stty> program, with varying degrees of portability.
255 You can also do this for most systems using the C<Term::ReadKey> module
256 from CPAN, which is easier to use and in theory more portable.
261 $password = ReadLine(0);
263 =head2 How do I read and write the serial port?
265 This depends on which operating system your program is running on. In
266 the case of Unix, the serial ports will be accessible through files in
267 /dev; on other systems, device names will doubtless differ.
268 Several problem areas common to all device interaction are the
275 Your system may use lockfiles to control multiple access. Make sure
276 you follow the correct protocol. Unpredictable behavior can result
277 from multiple processes reading from one device.
281 If you expect to use both read and write operations on the device,
282 you'll have to open it for update (see L<perlfunc/"open"> for
283 details). You may wish to open it without running the risk of
284 blocking by using C<sysopen()> and C<O_RDWR|O_NDELAY|O_NOCTTY> from the
285 C<Fcntl> module (part of the standard perl distribution). See
286 L<perlfunc/"sysopen"> for more on this approach.
290 Some devices will be expecting a "\r" at the end of each line rather
291 than a "\n". In some ports of perl, "\r" and "\n" are different from
292 their usual (Unix) ASCII values of "\012" and "\015". You may have to
293 give the numeric values you want directly, using octal ("\015"), hex
294 ("0x0D"), or as a control-character specification ("\cM").
296 print DEV "atv1\012"; # wrong, for some devices
297 print DEV "atv1\015"; # right, for some devices
299 Even though with normal text files a "\n" will do the trick, there is
300 still no unified scheme for terminating a line that is portable
301 between Unix, DOS/Win, and Macintosh, except to terminate I<ALL> line
302 ends with "\015\012", and strip what you don't need from the output.
303 This applies especially to socket I/O and autoflushing, discussed
306 =item flushing output
308 If you expect characters to get to your device when you C<print()> them,
309 you'll want to autoflush that filehandle. You can use C<select()>
310 and the C<$|> variable to control autoflushing (see L<perlvar/$E<verbar>>
311 and L<perlfunc/select>, or L<perlfaq5>, "How do I flush/unbuffer an
312 output filehandle? Why must I do this?"):
318 You'll also see code that does this without a temporary variable, as in
320 select((select(DEV), $| = 1)[0]);
322 Or if you don't mind pulling in a few thousand lines
323 of code just because you're afraid of a little C<$|> variable:
328 As mentioned in the previous item, this still doesn't work when using
329 socket I/O between Unix and Macintosh. You'll need to hard code your
330 line terminators, in that case.
332 =item non-blocking input
334 If you are doing a blocking C<read()> or C<sysread()>, you'll have to
335 arrange for an alarm handler to provide a timeout (see
336 L<perlfunc/alarm>). If you have a non-blocking open, you'll likely
337 have a non-blocking read, which means you may have to use a 4-arg
338 C<select()> to determine whether I/O is ready on that device (see
339 L<perlfunc/"select">.
343 While trying to read from his caller-id box, the notorious Jamie
344 Zawinski C<< <jwz@netscape.com> >>, after much gnashing of teeth and
345 fighting with C<sysread>, C<sysopen>, POSIX's C<tcgetattr> business,
346 and various other functions that go bump in the night, finally came up
351 my $stty = `/bin/stty -g`;
352 open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
353 # starting cu hoses /dev/tty's stty settings, even when it has
354 # been opened on a pipe...
355 system("/bin/stty $stty");
358 if ( !m/^Connected/ ) {
359 print STDERR "$0: cu printed `$_' instead of `Connected'\n";
363 =head2 How do I decode encrypted password files?
365 You spend lots and lots of money on dedicated hardware, but this is
366 bound to get you talked about.
368 Seriously, you can't if they are Unix password files--the Unix
369 password system employs one-way encryption. It's more like hashing
370 than encryption. The best you can do is check whether something else
371 hashes to the same string. You can't turn a hash back into the
372 original string. Programs like Crack can forcibly (and intelligently)
373 try to guess passwords, but don't (can't) guarantee quick success.
375 If you're worried about users selecting bad passwords, you should
376 proactively check when they try to change their password (by modifying
377 passwd(1), for example).
379 =head2 How do I start a process in the background?
381 (contributed by brian d foy)
383 There's not a single way to run code in the background so you don't
384 have to wait for it to finish before your program moves on to other
385 tasks. Process management depends on your particular operating system,
386 and many of the techniques are in L<perlipc>.
388 Several CPAN modules may be able to help, including C<IPC::Open2> or
389 C<IPC::Open3>, C<IPC::Run>, C<Parallel::Jobs>,
390 C<Parallel::ForkManager>, C<POE>, C<Proc::Background>, and
391 C<Win32::Process>. There are many other modules you might use, so
392 check those namespaces for other options too.
394 If you are on a Unix-like system, you might be able to get away with a
395 system call where you put an C<&> on the end of the command:
399 You can also try using C<fork>, as described in L<perlfunc> (although
400 this is the same thing that many of the modules will do for you).
404 =item STDIN, STDOUT, and STDERR are shared
406 Both the main process and the backgrounded one (the "child" process)
407 share the same STDIN, STDOUT and STDERR filehandles. If both try to
408 access them at once, strange things can happen. You may want to close
409 or reopen these for the child. You can get around this with
410 C<open>ing a pipe (see L<perlfunc/"open">) but on some systems this
411 means that the child process cannot outlive the parent.
415 You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too.
416 SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is
417 sent when you write to a filehandle whose child process has closed (an
418 untrapped SIGPIPE can cause your program to silently die). This is
419 not an issue with C<system("cmd&")>.
423 You have to be prepared to "reap" the child process when it finishes.
425 $SIG{CHLD} = sub { wait };
427 $SIG{CHLD} = 'IGNORE';
429 You can also use a double fork. You immediately C<wait()> for your
430 first child, and the init daemon will C<wait()> for your grandchild once
433 unless ($pid = fork) {
435 exec "what you really wanna do";
442 See L<perlipc/"Signals"> for other examples of code to do this.
443 Zombies are not an issue with C<system("prog &")>.
447 =head2 How do I trap control characters/signals?
449 You don't actually "trap" a control character. Instead, that character
450 generates a signal which is sent to your terminal's currently
451 foregrounded process group, which you then trap in your process.
452 Signals are documented in L<perlipc/"Signals"> and the
453 section on "Signals" in the Camel.
455 You can set the values of the C<%SIG> hash to be the functions you want
456 to handle the signal. After perl catches the signal, it looks in C<%SIG>
457 for a key with the same name as the signal, then calls the subroutine
460 # as an anonymous subroutine
462 $SIG{INT} = sub { syswrite(STDERR, "ouch\n", 5 ) };
464 # or a reference to a function
468 # or the name of the function as a string
472 Perl versions before 5.8 had in its C source code signal handlers which
473 would catch the signal and possibly run a Perl function that you had set
474 in C<%SIG>. This violated the rules of signal handling at that level
475 causing perl to dump core. Since version 5.8.0, perl looks at C<%SIG>
476 B<after> the signal has been caught, rather than while it is being caught.
477 Previous versions of this answer were incorrect.
479 =head2 How do I modify the shadow password file on a Unix system?
481 If perl was installed correctly and your shadow library was written
482 properly, the C<getpw*()> functions described in L<perlfunc> should in
483 theory provide (read-only) access to entries in the shadow password
484 file. To change the file, make a new shadow password file (the format
485 varies from system to system--see L<passwd> for specifics) and use
486 C<pwd_mkdb(8)> to install it (see L<pwd_mkdb> for more details).
488 =head2 How do I set the time and date?
490 Assuming you're running under sufficient permissions, you should be
491 able to set the system-wide date and time by running the C<date(1)>
492 program. (There is no way to set the time and date on a per-process
493 basis.) This mechanism will work for Unix, MS-DOS, Windows, and NT;
494 the VMS equivalent is C<set time>.
496 However, if all you want to do is change your time zone, you can
497 probably get away with setting an environment variable:
499 $ENV{TZ} = "MST7MDT"; # Unixish
500 $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
501 system "trn comp.lang.perl.misc";
503 =head2 How can I sleep() or alarm() for under a second?
504 X<Time::HiRes> X<BSD::Itimer> X<sleep> X<select>
506 If you want finer granularity than the 1 second that the C<sleep()>
507 function provides, the easiest way is to use the C<select()> function as
508 documented in L<perlfunc/"select">. Try the C<Time::HiRes> and
509 the C<BSD::Itimer> modules (available from CPAN, and starting from
510 Perl 5.8 C<Time::HiRes> is part of the standard distribution).
512 =head2 How can I measure time under a second?
513 X<Time::HiRes> X<BSD::Itimer> X<sleep> X<select>
515 (contributed by brian d foy)
517 The C<Time::HiRes> module (part of the standard distribution as of
518 Perl 5.8) measures time with the C<gettimeofday()> system call, which
519 returns the time in microseconds since the epoch. If you can't install
520 C<Time::HiRes> for older Perls and you are on a Unixish system, you
521 may be able to call C<gettimeofday(2)> directly. See
524 =head2 How can I do an atexit() or setjmp()/longjmp()? (Exception handling)
526 Release 5 of Perl added the END block, which can be used to simulate
527 C<atexit()>. Each package's END block is called when the program or
528 thread ends (see L<perlmod> manpage for more details).
530 For example, you can use this to make sure your filter program
531 managed to finish its output without filling up the disk:
534 close(STDOUT) || die "stdout close failed: $!";
537 The C<END> block isn't called when untrapped signals kill the program,
538 though, so if you use C<END> blocks you should also use
540 use sigtrap qw(die normal-signals);
542 Perl's exception-handling mechanism is its C<eval()> operator. You
543 can use C<eval()> as C<setjmp> and C<die()> as C<longjmp>. For
544 details of this, see the section on signals, especially the time-out
545 handler for a blocking C<flock()> in L<perlipc/"Signals"> or the
546 section on "Signals" in the Camel Book.
548 If exception handling is all you're interested in, try the
549 C<exceptions.pl> library (part of the standard perl distribution).
551 If you want the atexit() syntax (and an rmexit() as well), try the
552 AtExit module available from CPAN.
554 =head2 Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean?
556 Some Sys-V based systems, notably Solaris 2.X, redefined some of the
557 standard socket constants. Since these were constant across all
558 architectures, they were often hardwired into perl code. The proper
559 way to deal with this is to "use Socket" to get the correct values.
561 Note that even though SunOS and Solaris are binary compatible, these
562 values are different. Go figure.
564 =head2 How can I call my system's unique C functions from Perl?
566 In most cases, you write an external module to do it--see the answer
567 to "Where can I learn about linking C with Perl? [h2xs, xsubpp]".
568 However, if the function is a system call, and your system supports
569 C<syscall()>, you can use the C<syscall> function (documented in
572 Remember to check the modules that came with your distribution, and
573 CPAN as well--someone may already have written a module to do it. On
574 Windows, try C<Win32::API>. On Macs, try C<Mac::Carbon>. If no module
575 has an interface to the C function, you can inline a bit of C in your
576 Perl source with C<Inline::C>.
578 =head2 Where do I get the include files to do ioctl() or syscall()?
580 Historically, these would be generated by the C<h2ph> tool, part of the
581 standard perl distribution. This program converts C<cpp(1)> directives
582 in C header files to files containing subroutine definitions, like
583 C<&SYS_getitimer>, which you can use as arguments to your functions.
584 It doesn't work perfectly, but it usually gets most of the job done.
585 Simple files like F<errno.h>, F<syscall.h>, and F<socket.h> were fine,
586 but the hard ones like F<ioctl.h> nearly always need to be hand-edited.
587 Here's how to install the *.ph files:
593 If your system supports dynamic loading, for reasons of portability and
594 sanity you probably ought to use C<h2xs> (also part of the standard perl
595 distribution). This tool converts C header files to Perl extensions.
596 See L<perlxstut> for how to get started with C<h2xs>.
598 If your system doesn't support dynamic loading, you still probably
599 ought to use C<h2xs>. See L<perlxstut> and L<ExtUtils::MakeMaker> for
600 more information (in brief, just use B<make perl> instead of a plain
601 B<make> to rebuild perl with a new static extension).
603 =head2 Why do setuid perl scripts complain about kernel problems?
605 Some operating systems have bugs in the kernel that make setuid
606 scripts inherently insecure. Perl gives you a number of options
607 (described in L<perlsec>) to work around such systems.
609 =head2 How can I open a pipe both to and from a command?
611 The C<IPC::Open2> module (part of the standard perl distribution) is
612 an easy-to-use approach that internally uses C<pipe()>, C<fork()>, and
613 C<exec()> to do the job. Make sure you read the deadlock warnings in
614 its documentation, though (see L<IPC::Open2>). See
615 L<perlipc/"Bidirectional Communication with Another Process"> and
616 L<perlipc/"Bidirectional Communication with Yourself">
618 You may also use the C<IPC::Open3> module (part of the standard perl
619 distribution), but be warned that it has a different order of
620 arguments from C<IPC::Open2> (see L<IPC::Open3>).
622 =head2 Why can't I get the output of a command with system()?
624 You're confusing the purpose of C<system()> and backticks (``). C<system()>
625 runs a command and returns exit status information (as a 16 bit value:
626 the low 7 bits are the signal the process died from, if any, and
627 the high 8 bits are the actual exit value). Backticks (``) run a
628 command and return what it sent to STDOUT.
630 $exit_status = system("mail-users");
631 $output_string = `ls`;
633 =head2 How can I capture STDERR from an external command?
635 There are three basic ways of running external commands:
637 system $cmd; # using system()
638 $output = `$cmd`; # using backticks (``)
639 open (PIPE, "cmd |"); # using open()
641 With C<system()>, both STDOUT and STDERR will go the same place as the
642 script's STDOUT and STDERR, unless the C<system()> command redirects them.
643 Backticks and C<open()> read B<only> the STDOUT of your command.
645 You can also use the C<open3()> function from C<IPC::Open3>. Benjamin
646 Goldberg provides some sample code:
648 To capture a program's STDOUT, but discard its STDERR:
652 use Symbol qw(gensym);
653 open(NULL, ">", File::Spec->devnull);
654 my $pid = open3(gensym, \*PH, ">&NULL", "cmd");
658 To capture a program's STDERR, but discard its STDOUT:
662 use Symbol qw(gensym);
663 open(NULL, ">", File::Spec->devnull);
664 my $pid = open3(gensym, ">&NULL", \*PH, "cmd");
668 To capture a program's STDERR, and let its STDOUT go to our own STDERR:
671 use Symbol qw(gensym);
672 my $pid = open3(gensym, ">&STDERR", \*PH, "cmd");
676 To read both a command's STDOUT and its STDERR separately, you can
677 redirect them to temp files, let the command run, then read the temp
681 use Symbol qw(gensym);
683 local *CATCHOUT = IO::File->new_tmpfile;
684 local *CATCHERR = IO::File->new_tmpfile;
685 my $pid = open3(gensym, ">&CATCHOUT", ">&CATCHERR", "cmd");
687 seek $_, 0, 0 for \*CATCHOUT, \*CATCHERR;
688 while( <CATCHOUT> ) {}
689 while( <CATCHERR> ) {}
691 But there's no real need for B<both> to be tempfiles... the following
692 should work just as well, without deadlocking:
695 use Symbol qw(gensym);
697 local *CATCHERR = IO::File->new_tmpfile;
698 my $pid = open3(gensym, \*CATCHOUT, ">&CATCHERR", "cmd");
699 while( <CATCHOUT> ) {}
702 while( <CATCHERR> ) {}
704 And it'll be faster, too, since we can begin processing the program's
705 stdout immediately, rather than waiting for the program to finish.
707 With any of these, you can change file descriptors before the call:
709 open(STDOUT, ">logfile");
712 or you can use Bourne shell file-descriptor redirection:
714 $output = `$cmd 2>some_file`;
715 open (PIPE, "cmd 2>some_file |");
717 You can also use file-descriptor redirection to make STDERR a
720 $output = `$cmd 2>&1`;
721 open (PIPE, "cmd 2>&1 |");
723 Note that you I<cannot> simply open STDERR to be a dup of STDOUT
724 in your Perl program and avoid calling the shell to do the redirection.
727 open(STDERR, ">&STDOUT");
728 $alloutput = `cmd args`; # stderr still escapes
730 This fails because the C<open()> makes STDERR go to where STDOUT was
731 going at the time of the C<open()>. The backticks then make STDOUT go to
732 a string, but don't change STDERR (which still goes to the old
735 Note that you I<must> use Bourne shell (C<sh(1)>) redirection syntax in
736 backticks, not C<csh(1)>! Details on why Perl's C<system()> and backtick
737 and pipe opens all use the Bourne shell are in the
738 F<versus/csh.whynot> article in the "Far More Than You Ever Wanted To
739 Know" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz . To
740 capture a command's STDERR and STDOUT together:
742 $output = `cmd 2>&1`; # either with backticks
743 $pid = open(PH, "cmd 2>&1 |"); # or with an open pipe
744 while (<PH>) { } # plus a read
746 To capture a command's STDOUT but discard its STDERR:
748 $output = `cmd 2>/dev/null`; # either with backticks
749 $pid = open(PH, "cmd 2>/dev/null |"); # or with an open pipe
750 while (<PH>) { } # plus a read
752 To capture a command's STDERR but discard its STDOUT:
754 $output = `cmd 2>&1 1>/dev/null`; # either with backticks
755 $pid = open(PH, "cmd 2>&1 1>/dev/null |"); # or with an open pipe
756 while (<PH>) { } # plus a read
758 To exchange a command's STDOUT and STDERR in order to capture the STDERR
759 but leave its STDOUT to come out our old STDERR:
761 $output = `cmd 3>&1 1>&2 2>&3 3>&-`; # either with backticks
762 $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
763 while (<PH>) { } # plus a read
765 To read both a command's STDOUT and its STDERR separately, it's easiest
766 to redirect them separately to files, and then read from those files
767 when the program is done:
769 system("program args 1>program.stdout 2>program.stderr");
771 Ordering is important in all these examples. That's because the shell
772 processes file descriptor redirections in strictly left to right order.
774 system("prog args 1>tmpfile 2>&1");
775 system("prog args 2>&1 1>tmpfile");
777 The first command sends both standard out and standard error to the
778 temporary file. The second command sends only the old standard output
779 there, and the old standard error shows up on the old standard out.
781 =head2 Why doesn't open() return an error when a pipe open fails?
783 If the second argument to a piped C<open()> contains shell
784 metacharacters, perl C<fork()>s, then C<exec()>s a shell to decode the
785 metacharacters and eventually run the desired program. If the program
786 couldn't be run, it's the shell that gets the message, not Perl. All
787 your Perl program can find out is whether the shell itself could be
788 successfully started. You can still capture the shell's STDERR and
789 check it for error messages. See L<"How can I capture STDERR from an
790 external command?"> elsewhere in this document, or use the
791 C<IPC::Open3> module.
793 If there are no shell metacharacters in the argument of C<open()>, Perl
794 runs the command directly, without using the shell, and can correctly
795 report whether the command started.
797 =head2 What's wrong with using backticks in a void context?
799 Strictly speaking, nothing. Stylistically speaking, it's not a good
800 way to write maintainable code. Perl has several operators for
801 running external commands. Backticks are one; they collect the output
802 from the command for use in your program. The C<system> function is
803 another; it doesn't do this.
805 Writing backticks in your program sends a clear message to the readers
806 of your code that you wanted to collect the output of the command.
807 Why send a clear message that isn't true?
813 You forgot to check C<$?> to see whether the program even ran
814 correctly. Even if you wrote
816 print `cat /etc/termcap`;
818 this code could and probably should be written as
820 system("cat /etc/termcap") == 0
821 or die "cat program failed!";
823 which will echo the cat command's output as it is generated, instead
824 of waiting until the program has completed to print it out. It also
825 checks the return value.
827 C<system> also provides direct control over whether shell wildcard
828 processing may take place, whereas backticks do not.
830 =head2 How can I call backticks without shell processing?
832 This is a bit tricky. You can't simply write the command
835 @ok = `grep @opts '$search_string' @filenames`;
837 As of Perl 5.8.0, you can use C<open()> with multiple arguments.
838 Just like the list forms of C<system()> and C<exec()>, no shell
841 open( GREP, "-|", 'grep', @opts, $search_string, @filenames );
848 if (open(GREP, "-|")) {
855 exec 'grep', @opts, $search_string, @filenames;
858 Just as with C<system()>, no shell escapes happen when you C<exec()> a
859 list. Further examples of this can be found in L<perlipc/"Safe Pipe
862 Note that if you're using Windows, no solution to this vexing issue is
863 even possible. Even if Perl were to emulate C<fork()>, you'd still be
864 stuck, because Windows does not have an argc/argv-style API.
866 =head2 Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?
868 This happens only if your perl is compiled to use stdio instead of
869 perlio, which is the default. Some (maybe all?) stdios set error and
870 eof flags that you may need to clear. The C<POSIX> module defines
871 C<clearerr()> that you can use. That is the technically correct way to
872 do it. Here are some less reliable workarounds:
878 Try keeping around the seekpointer and go there, like this:
881 seek(LOG, $where, 0);
885 If that doesn't work, try seeking to a different part of the file and
890 If that doesn't work, try seeking to a different part of
891 the file, reading something, and then seeking back.
895 If that doesn't work, give up on your stdio package and use sysread.
899 =head2 How can I convert my shell script to perl?
901 Learn Perl and rewrite it. Seriously, there's no simple converter.
902 Things that are awkward to do in the shell are easy to do in Perl, and
903 this very awkwardness is what would make a shell->perl converter
904 nigh-on impossible to write. By rewriting it, you'll think about what
905 you're really trying to do, and hopefully will escape the shell's
906 pipeline datastream paradigm, which while convenient for some matters,
907 causes many inefficiencies.
909 =head2 Can I use perl to run a telnet or ftp session?
911 Try the C<Net::FTP>, C<TCP::Client>, and C<Net::Telnet> modules
912 (available from CPAN).
913 http://www.cpan.org/scripts/netstuff/telnet.emul.shar will also help
914 for emulating the telnet protocol, but C<Net::Telnet> is quite
915 probably easier to use.
917 If all you want to do is pretend to be telnet but don't need
918 the initial telnet handshaking, then the standard dual-process
919 approach will suffice:
921 use IO::Socket; # new in 5.004
922 $handle = IO::Socket::INET->new('www.perl.com:80')
923 or die "can't connect to port 80 on www.perl.com: $!";
924 $handle->autoflush(1);
925 if (fork()) { # XXX: undef means failure
927 print while <STDIN>; # everything from stdin to socket
929 print while <$handle>; # everything from socket to stdout
934 =head2 How can I write expect in Perl?
936 Once upon a time, there was a library called L<chat2.pl> (part of the
937 standard perl distribution), which never really got finished. If you
938 find it somewhere, I<don't use it>. These days, your best bet is to
939 look at the Expect module available from CPAN, which also requires two
940 other modules from CPAN, C<IO::Pty> and C<IO::Stty>.
942 =head2 Is there a way to hide perl's command line from programs such as "ps"?
944 First of all note that if you're doing this for security reasons (to
945 avoid people seeing passwords, for example) then you should rewrite
946 your program so that critical information is never given as an
947 argument. Hiding the arguments won't make your program completely
950 To actually alter the visible command line, you can assign to the
951 variable $0 as documented in L<perlvar>. This won't work on all
952 operating systems, though. Daemon programs like sendmail place their
955 $0 = "orcus [accepting connections]";
957 =head2 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?
963 In the strictest sense, it can't be done--the script executes as a
964 different process from the shell it was started from. Changes to a
965 process are not reflected in its parent--only in any children
966 created after the change. There is shell magic that may allow you to
967 fake it by C<eval()>ing the script's output in your shell; check out the
968 comp.unix.questions FAQ for details.
972 =head2 How do I close a process's filehandle without waiting for it to complete?
974 Assuming your system supports such things, just send an appropriate signal
975 to the process (see L<perlfunc/"kill">). It's common to first send a TERM
976 signal, wait a little bit, and then send a KILL signal to finish it off.
978 =head2 How do I fork a daemon process?
980 If by daemon process you mean one that's detached (disassociated from
981 its tty), then the following process is reported to work on most
982 Unixish systems. Non-Unix users should check their Your_OS::Process
983 module for other solutions.
989 Open /dev/tty and use the TIOCNOTTY ioctl on it. See L<tty>
990 for details. Or better yet, you can just use the C<POSIX::setsid()>
991 function, so you don't have to worry about process groups.
995 Change directory to /
999 Reopen STDIN, STDOUT, and STDERR so they're not connected to the old
1004 Background yourself like this:
1010 The C<Proc::Daemon> module, available from CPAN, provides a function to
1011 perform these actions for you.
1013 =head2 How do I find out if I'm running interactively or not?
1015 (contributed by brian d foy)
1017 This is a difficult question to answer, and the best answer is
1020 What do you really want to know? If you merely want to know if one of
1021 your filehandles is connected to a terminal, you can try the C<-t>
1025 print "I'm connected to a terminal!\n";
1028 However, you might be out of luck if you expect that means there is a
1029 real person on the other side. With the C<Expect> module, another
1030 program can pretend to be a person. The program might even come close
1031 to passing the Turing test.
1033 The C<IO::Interactive> module does the best it can to give you an
1034 answer. Its C<is_interactive> function returns an output filehandle;
1035 that filehandle points to standard output if the module thinks the
1036 session is interactive. Otherwise, the filehandle is a null handle
1037 that simply discards the output:
1039 use IO::Interactive;
1041 print { is_interactive } "I might go to standard output!\n";
1043 This still doesn't guarantee that a real person is answering your
1044 prompts or reading your output.
1046 If you want to know how to handle automated testing for your
1047 distribution, you can check the environment. The CPAN
1048 Testers, for instance, set the value of C<AUTOMATED_TESTING>:
1050 unless( $ENV{AUTOMATED_TESTING} ) {
1051 print "Hello interactive tester!\n";
1054 =head2 How do I timeout a slow event?
1056 Use the C<alarm()> function, probably in conjunction with a signal
1057 handler, as documented in L<perlipc/"Signals"> and the section on
1058 "Signals" in the Camel. You may instead use the more flexible
1059 C<Sys::AlarmCall> module available from CPAN.
1061 The C<alarm()> function is not implemented on all versions of Windows.
1062 Check the documentation for your specific version of Perl.
1064 =head2 How do I set CPU limits?
1065 X<BSD::Resource> X<limit> X<CPU>
1067 (contributed by Xho)
1069 Use the C<BSD::Resource> module from CPAN. As an example:
1072 setrlimit(RLIMIT_CPU,10,20) or die $!;
1074 This sets the soft and hard limits to 10 and 20 seconds, respectively.
1075 After 10 seconds of time spent running on the CPU (not "wall" time),
1076 the process will be sent a signal (XCPU on some systems) which, if not
1077 trapped, will cause the process to terminate. If that signal is
1078 trapped, then after 10 more seconds (20 seconds in total) the process
1079 will be killed with a non-trappable signal.
1081 See the C<BSD::Resource> and your systems documentation for the gory
1084 =head2 How do I avoid zombies on a Unix system?
1086 Use the reaper code from L<perlipc/"Signals"> to call C<wait()> when a
1087 SIGCHLD is received, or else use the double-fork technique described
1088 in L<perlfaq8/"How do I start a process in the background?">.
1090 =head2 How do I use an SQL database?
1092 The C<DBI> module provides an abstract interface to most database
1093 servers and types, including Oracle, DB2, Sybase, mysql, Postgresql,
1094 ODBC, and flat files. The DBI module accesses each database type
1095 through a database driver, or DBD. You can see a complete list of
1096 available drivers on CPAN: http://www.cpan.org/modules/by-module/DBD/ .
1097 You can read more about DBI on http://dbi.perl.org .
1099 Other modules provide more specific access: C<Win32::ODBC>, C<Alzabo>,
1100 C<iodbc>, and others found on CPAN Search: http://search.cpan.org .
1102 =head2 How do I make a system() exit on control-C?
1104 You can't. You need to imitate the C<system()> call (see L<perlipc> for
1105 sample code) and then have a signal handler for the INT signal that
1106 passes the signal on to the subprocess. Or you can check for it:
1109 if ($rc & 127) { die "signal death" }
1111 =head2 How do I open a file without blocking?
1113 If you're lucky enough to be using a system that supports
1114 non-blocking reads (most Unixish systems do), you need only to use the
1115 C<O_NDELAY> or C<O_NONBLOCK> flag from the C<Fcntl> module in conjunction with
1119 sysopen(FH, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)
1120 or die "can't open /foo/somefile: $!":
1122 =head2 How do I tell the difference between errors from the shell and perl?
1124 (answer contributed by brian d foy)
1126 When you run a Perl script, something else is running the script for you,
1127 and that something else may output error messages. The script might
1128 emit its own warnings and error messages. Most of the time you cannot
1131 You probably cannot fix the thing that runs perl, but you can change how
1132 perl outputs its warnings by defining a custom warning and die functions.
1134 Consider this script, which has an error you may not notice immediately.
1136 #!/usr/locl/bin/perl
1138 print "Hello World\n";
1140 I get an error when I run this from my shell (which happens to be
1141 bash). That may look like perl forgot it has a C<print()> function,
1142 but my shebang line is not the path to perl, so the shell runs the
1143 script, and I get the error.
1146 ./test: line 3: print: command not found
1148 A quick and dirty fix involves a little bit of code, but this may be all
1149 you need to figure out the problem.
1154 $SIG{__WARN__} = sub{ print STDERR "Perl: ", @_; };
1155 $SIG{__DIE__} = sub{ print STDERR "Perl: ", @_; exit 1};
1162 The perl message comes out with "Perl" in front. The C<BEGIN> block
1163 works at compile time so all of the compilation errors and warnings
1164 get the "Perl:" prefix too.
1166 Perl: Useless use of division (/) in void context at ./test line 9.
1167 Perl: Name "main::a" used only once: possible typo at ./test line 8.
1168 Perl: Name "main::x" used only once: possible typo at ./test line 9.
1169 Perl: Use of uninitialized value in addition (+) at ./test line 8.
1170 Perl: Use of uninitialized value in division (/) at ./test line 9.
1171 Perl: Illegal division by zero at ./test line 9.
1172 Perl: Illegal division by zero at -e line 3.
1174 If I don't see that "Perl:", it's not from perl.
1176 You could also just know all the perl errors, and although there are
1177 some people who may know all of them, you probably don't. However, they
1178 all should be in the L<perldiag> manpage. If you don't find the error in
1179 there, it probably isn't a perl error.
1181 Looking up every message is not the easiest way, so let perl to do it
1182 for you. Use the diagnostics pragma with turns perl's normal messages
1183 into longer discussions on the topic.
1187 If you don't get a paragraph or two of expanded discussion, it
1188 might not be perl's message.
1190 =head2 How do I install a module from CPAN?
1192 (contributed by brian d foy)
1194 The easiest way is to have a module also named CPAN do it for you by using
1195 the C<cpan> command the comes with Perl. You can give it a list of modules
1198 $ cpan IO::Interactive Getopt::Whatever
1200 If you prefer C<CPANPLUS>, it's just as easy:
1202 $ cpanp i IO::Interactive Getopt::Whatever
1204 If you want to install a distribution from the current directory, you can
1205 tell C<CPAN.pm> to install C<.> (the full stop):
1209 See the documentation for either of those commands to see what else
1212 If you want to try to install a distribution by yourself, resolving
1213 all dependencies on your own, you follow one of two possible build
1216 For distributions that use I<Makefile.PL>:
1221 For distributions that use I<Build.PL>:
1227 Some distributions may need to link to libraries or other third-party
1228 code and their build and installation sequences may be more complicated.
1229 Check any I<README> or I<INSTALL> files that you may find.
1231 =head2 What's the difference between require and use?
1233 (contributed by brian d foy)
1235 Perl runs C<require> statement at run-time. Once Perl loads, compiles,
1236 and runs the file, it doesn't do anything else. The C<use> statement
1237 is the same as a C<require> run at compile-time, but Perl also calls the
1238 C<import> method for the loaded package. These two are the same:
1240 use MODULE qw(import list);
1244 MODULE->import(import list);
1247 However, you can suppress the C<import> by using an explicit, empty
1248 import list. Both of these still happen at compile-time:
1256 Since C<use> will also call the C<import> method, the actual value
1257 for C<MODULE> must be a bareword. That is, C<use> cannot load files
1258 by name, although C<require> can:
1260 require "$ENV{HOME}/lib/Foo.pm"; # no @INC searching!
1262 See the entry for C<use> in L<perlfunc> for more details.
1264 =head2 How do I keep my own module/library directory?
1266 When you build modules, tell Perl where to install the modules.
1268 For C<Makefile.PL>-based distributions, use the INSTALL_BASE option
1269 when generating Makefiles:
1271 perl Makefile.PL INSTALL_BASE=/mydir/perl
1273 You can set this in your C<CPAN.pm> configuration so modules
1274 automatically install in your private library directory when you use
1278 cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
1281 For C<Build.PL>-based distributions, use the --install_base option:
1283 perl Build.PL --install_base /mydir/perl
1285 You can configure C<CPAN.pm> to automatically use this option too:
1288 cpan> o conf mbuild_arg "--install_base /mydir/perl"
1291 INSTALL_BASE tells these tools to put your modules into
1292 F</mydir/perl/lib/perl5>. See L<How do I add a directory to my
1293 include path (@INC) at runtime?> for details on how to run your newly
1296 There is one caveat with INSTALL_BASE, though, since it acts
1297 differently than the PREFIX and LIB settings that older versions of
1298 C<ExtUtils::MakeMaker> advocated. INSTALL_BASE does not support
1299 installing modules for multiple versions of Perl or different
1300 architectures under the same directory. You should consider if you
1301 really want that , and if you do, use the older PREFIX and LIB
1302 settings. See the C<ExtUtils::Makemaker> documentation for more details.
1304 =head2 How do I add the directory my program lives in to the module/library search path?
1306 (contributed by brian d foy)
1308 If you know the directory already, you can add it to C<@INC> as you would
1309 for any other directory. You might <use lib> if you know the directory
1314 The trick in this task is to find the directory. Before your script does
1315 anything else (such as a C<chdir>), you can get the current working
1316 directory with the C<Cwd> module, which comes with Perl:
1320 our $directory = cwd;
1325 You can do a similar thing with the value of C<$0>, which holds the
1326 script name. That might hold a relative path, but C<rel2abs> can turn
1327 it into an absolute path. Once you have the
1330 use File::Spec::Functions qw(rel2abs);
1331 use File::Basename qw(dirname);
1333 my $path = rel2abs( $0 );
1334 our $directory = dirname( $path );
1339 The C<FindBin> module, which comes with Perl, might work. It finds the
1340 directory of the currently running script and puts it in C<$Bin>, which
1341 you can then use to construct the right library path:
1343 use FindBin qw($Bin);
1345 =head2 How do I add a directory to my include path (@INC) at runtime?
1347 Here are the suggested ways of modifying your include path, including
1348 environment variables, run-time switches, and in-code statements:
1352 =item the PERLLIB environment variable
1354 $ export PERLLIB=/path/to/my/dir
1357 =item the PERL5LIB environment variable
1359 $ export PERL5LIB=/path/to/my/dir
1362 =item the perl -Idir command line flag
1364 $ perl -I/path/to/my/dir program.pl
1366 =item the use lib pragma:
1368 use lib "$ENV{HOME}/myown_perllib";
1372 The last is particularly useful because it knows about machine
1373 dependent architectures. The C<lib.pm> pragmatic module was first
1374 included with the 5.002 release of Perl.
1376 =head2 What is socket.ph and where do I get it?
1378 It's a Perl 4 style file defining values for system networking
1379 constants. Sometimes it is built using C<h2ph> when Perl is installed,
1380 but other times it is not. Modern programs C<use Socket;> instead.
1382 =head1 AUTHOR AND COPYRIGHT
1384 Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and
1385 other authors as noted. All rights reserved.
1387 This documentation is free; you can redistribute it and/or modify it
1388 under the same terms as Perl itself.
1390 Irrespective of its distribution, all code examples in this file
1391 are hereby placed into the public domain. You are permitted and
1392 encouraged to use this code in your own programs for fun
1393 or for profit as you see fit. A simple comment in the code giving
1394 credit would be courteous but is not required.