1PERLFAQ8(1)            Perl Programmers Reference Guide            PERLFAQ8(1)
2
3
4

NAME

6       perlfaq8 - System Interaction
7

DESCRIPTION

9       This section of the Perl FAQ covers questions involving operating
10       system interaction.  Topics include interprocess communication (IPC),
11       control over the user-interface (keyboard, screen and pointing
12       devices), and most anything else not related to data manipulation.
13
14       Read the FAQs and documentation specific to the port of perl to your
15       operating system (eg, perlvms, perlplan9, ...).  These should contain
16       more detailed information on the vagaries of your perl.
17
18   How do I find out which operating system I'm running under?
19       The $^O variable ($OSNAME if you use "English") contains an indication
20       of the name of the operating system (not its release number) that your
21       perl binary was built for.
22
23   How come exec() doesn't return?
24       (contributed by brian d foy)
25
26       The "exec" function's job is to turn your process into another command
27       and never to return. If that's not what you want to do, don't use
28       "exec". :)
29
30       If you want to run an external command and still keep your Perl process
31       going, look at a piped "open", "fork", or "system".
32
33   How do I do fancy stuff with the keyboard/screen/mouse?
34       How you access/control keyboards, screens, and pointing devices
35       ("mice") is system-dependent.  Try the following modules:
36
37       Keyboard
38                   Term::Cap               Standard perl distribution
39                   Term::ReadKey           CPAN
40                   Term::ReadLine::Gnu     CPAN
41                   Term::ReadLine::Perl    CPAN
42                   Term::Screen            CPAN
43
44       Screen
45                   Term::Cap               Standard perl distribution
46                   Curses                  CPAN
47                   Term::ANSIColor         CPAN
48
49       Mouse
50                   Tk                      CPAN
51
52       Some of these specific cases are shown as examples in other answers in
53       this section of the perlfaq.
54
55   How do I print something out in color?
56       In general, you don't, because you don't know whether the recipient has
57       a color-aware display device.  If you know that they have an ANSI
58       terminal that understands color, you can use the "Term::ANSIColor"
59       module from CPAN:
60
61               use Term::ANSIColor;
62               print color("red"), "Stop!\n", color("reset");
63               print color("green"), "Go!\n", color("reset");
64
65       Or like this:
66
67               use Term::ANSIColor qw(:constants);
68               print RED, "Stop!\n", RESET;
69               print GREEN, "Go!\n", RESET;
70
71   How do I read just one key without waiting for a return key?
72       Controlling input buffering is a remarkably system-dependent matter.
73       On many systems, you can just use the stty command as shown in "getc"
74       in perlfunc, but as you see, that's already getting you into
75       portability snags.
76
77               open(TTY, "+</dev/tty") or die "no tty: $!";
78               system "stty  cbreak </dev/tty >/dev/tty 2>&1";
79               $key = getc(TTY);               # perhaps this works
80               # OR ELSE
81               sysread(TTY, $key, 1);  # probably this does
82               system "stty -cbreak </dev/tty >/dev/tty 2>&1";
83
84       The "Term::ReadKey" module from CPAN offers an easy-to-use interface
85       that should be more efficient than shelling out to stty for each key.
86       It even includes limited support for Windows.
87
88               use Term::ReadKey;
89               ReadMode('cbreak');
90               $key = ReadKey(0);
91               ReadMode('normal');
92
93       However, using the code requires that you have a working C compiler and
94       can use it to build and install a CPAN module.  Here's a solution using
95       the standard "POSIX" module, which is already on your system (assuming
96       your system supports POSIX).
97
98               use HotKey;
99               $key = readkey();
100
101       And here's the "HotKey" module, which hides the somewhat mystifying
102       calls to manipulate the POSIX termios structures.
103
104               # HotKey.pm
105               package HotKey;
106
107               @ISA = qw(Exporter);
108               @EXPORT = qw(cbreak cooked readkey);
109
110               use strict;
111               use POSIX qw(:termios_h);
112               my ($term, $oterm, $echo, $noecho, $fd_stdin);
113
114               $fd_stdin = fileno(STDIN);
115               $term     = POSIX::Termios->new();
116               $term->getattr($fd_stdin);
117               $oterm     = $term->getlflag();
118
119               $echo     = ECHO | ECHOK | ICANON;
120               $noecho   = $oterm & ~$echo;
121
122               sub cbreak {
123                       $term->setlflag($noecho);  # ok, so i don't want echo either
124                       $term->setcc(VTIME, 1);
125                       $term->setattr($fd_stdin, TCSANOW);
126               }
127
128               sub cooked {
129                       $term->setlflag($oterm);
130                       $term->setcc(VTIME, 0);
131                       $term->setattr($fd_stdin, TCSANOW);
132               }
133
134               sub readkey {
135                       my $key = '';
136                       cbreak();
137                       sysread(STDIN, $key, 1);
138                       cooked();
139                       return $key;
140               }
141
142               END { cooked() }
143
144               1;
145
146   How do I check whether input is ready on the keyboard?
147       The easiest way to do this is to read a key in nonblocking mode with
148       the "Term::ReadKey" module from CPAN, passing it an argument of -1 to
149       indicate not to block:
150
151               use Term::ReadKey;
152
153               ReadMode('cbreak');
154
155               if (defined ($char = ReadKey(-1)) ) {
156                       # input was waiting and it was $char
157               } else {
158                       # no input was waiting
159               }
160
161               ReadMode('normal');                  # restore normal tty settings
162
163   How do I clear the screen?
164       (contributed by brian d foy)
165
166       To clear the screen, you just have to print the special sequence that
167       tells the terminal to clear the screen. Once you have that sequence,
168       output it when you want to clear the screen.
169
170       You can use the "Term::ANSIScreen" module to get the special sequence.
171       Import the "cls" function (or the ":screen" tag):
172
173               use Term::ANSIScreen qw(cls);
174               my $clear_screen = cls();
175
176               print $clear_screen;
177
178       The "Term::Cap" module can also get the special sequence if you want to
179       deal with the low-level details of terminal control. The "Tputs" method
180       returns the string for the given capability:
181
182               use Term::Cap;
183
184               $terminal = Term::Cap->Tgetent( { OSPEED => 9600 } );
185               $clear_string = $terminal->Tputs('cl');
186
187               print $clear_screen;
188
189       On Windows, you can use the "Win32::Console" module. After creating an
190       object for the output filehandle you want to affect, call the "Cls"
191       method:
192
193               Win32::Console;
194
195               $OUT = Win32::Console->new(STD_OUTPUT_HANDLE);
196               my $clear_string = $OUT->Cls;
197
198               print $clear_screen;
199
200       If you have a command-line program that does the job, you can call it
201       in backticks to capture whatever it outputs so you can use it later:
202
203               $clear_string = `clear`;
204
205               print $clear_string;
206
207   How do I get the screen size?
208       If you have "Term::ReadKey" module installed from CPAN, you can use it
209       to fetch the width and height in characters and in pixels:
210
211               use Term::ReadKey;
212               ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
213
214       This is more portable than the raw "ioctl", but not as illustrative:
215
216               require 'sys/ioctl.ph';
217               die "no TIOCGWINSZ " unless defined &TIOCGWINSZ;
218               open(TTY, "+</dev/tty")                     or die "No tty: $!";
219               unless (ioctl(TTY, &TIOCGWINSZ, $winsize='')) {
220                       die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\n", &TIOCGWINSZ;
221               }
222               ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);
223               print "(row,col) = ($row,$col)";
224               print "  (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
225               print "\n";
226
227   How do I ask the user for a password?
228       (This question has nothing to do with the web.  See a different FAQ for
229       that.)
230
231       There's an example of this in "crypt" in perlfunc).  First, you put the
232       terminal into "no echo" mode, then just read the password normally.
233       You may do this with an old-style "ioctl()" function, POSIX terminal
234       control (see POSIX or its documentation the Camel Book), or a call to
235       the stty program, with varying degrees of portability.
236
237       You can also do this for most systems using the "Term::ReadKey" module
238       from CPAN, which is easier to use and in theory more portable.
239
240               use Term::ReadKey;
241
242               ReadMode('noecho');
243               $password = ReadLine(0);
244
245   How do I read and write the serial port?
246       This depends on which operating system your program is running on.  In
247       the case of Unix, the serial ports will be accessible through files in
248       /dev; on other systems, device names will doubtless differ.  Several
249       problem areas common to all device interaction are the following:
250
251       lockfiles
252           Your system may use lockfiles to control multiple access.  Make
253           sure you follow the correct protocol.  Unpredictable behavior can
254           result from multiple processes reading from one device.
255
256       open mode
257           If you expect to use both read and write operations on the device,
258           you'll have to open it for update (see "open" in perlfunc for
259           details).  You may wish to open it without running the risk of
260           blocking by using "sysopen()" and "O_RDWR|O_NDELAY|O_NOCTTY" from
261           the "Fcntl" module (part of the standard perl distribution).  See
262           "sysopen" in perlfunc for more on this approach.
263
264       end of line
265           Some devices will be expecting a "\r" at the end of each line
266           rather than a "\n".  In some ports of perl, "\r" and "\n" are
267           different from their usual (Unix) ASCII values of "\012" and
268           "\015".  You may have to give the numeric values you want directly,
269           using octal ("\015"), hex ("0x0D"), or as a control-character
270           specification ("\cM").
271
272                   print DEV "atv1\012";   # wrong, for some devices
273                   print DEV "atv1\015";   # right, for some devices
274
275           Even though with normal text files a "\n" will do the trick, there
276           is still no unified scheme for terminating a line that is portable
277           between Unix, DOS/Win, and Macintosh, except to terminate ALL line
278           ends with "\015\012", and strip what you don't need from the
279           output.  This applies especially to socket I/O and autoflushing,
280           discussed next.
281
282       flushing output
283           If you expect characters to get to your device when you "print()"
284           them, you'll want to autoflush that filehandle.  You can use
285           "select()" and the $| variable to control autoflushing (see "$|" in
286           perlvar and "select" in perlfunc, or perlfaq5, "How do I
287           flush/unbuffer an output filehandle?  Why must I do this?"):
288
289                   $oldh = select(DEV);
290                   $| = 1;
291                   select($oldh);
292
293           You'll also see code that does this without a temporary variable,
294           as in
295
296                   select((select(DEV), $| = 1)[0]);
297
298           Or if you don't mind pulling in a few thousand lines of code just
299           because you're afraid of a little $| variable:
300
301                   use IO::Handle;
302                   DEV->autoflush(1);
303
304           As mentioned in the previous item, this still doesn't work when
305           using socket I/O between Unix and Macintosh.  You'll need to hard
306           code your line terminators, in that case.
307
308       non-blocking input
309           If you are doing a blocking "read()" or "sysread()", you'll have to
310           arrange for an alarm handler to provide a timeout (see "alarm" in
311           perlfunc).  If you have a non-blocking open, you'll likely have a
312           non-blocking read, which means you may have to use a 4-arg
313           "select()" to determine whether I/O is ready on that device (see
314           "select" in perlfunc.
315
316       While trying to read from his caller-id box, the notorious Jamie
317       Zawinski "<jwz@netscape.com>", after much gnashing of teeth and
318       fighting with "sysread", "sysopen", POSIX's "tcgetattr" business, and
319       various other functions that go bump in the night, finally came up with
320       this:
321
322               sub open_modem {
323                       use IPC::Open2;
324                       my $stty = `/bin/stty -g`;
325                       open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
326                       # starting cu hoses /dev/tty's stty settings, even when it has
327                       # been opened on a pipe...
328                       system("/bin/stty $stty");
329                       $_ = <MODEM_IN>;
330                       chomp;
331                       if ( !m/^Connected/ ) {
332                               print STDERR "$0: cu printed `$_' instead of `Connected'\n";
333                       }
334               }
335
336   How do I decode encrypted password files?
337       You spend lots and lots of money on dedicated hardware, but this is
338       bound to get you talked about.
339
340       Seriously, you can't if they are Unix password files--the Unix password
341       system employs one-way encryption.  It's more like hashing than
342       encryption.  The best you can do is check whether something else hashes
343       to the same string.  You can't turn a hash back into the original
344       string. Programs like Crack can forcibly (and intelligently) try to
345       guess passwords, but don't (can't) guarantee quick success.
346
347       If you're worried about users selecting bad passwords, you should
348       proactively check when they try to change their password (by modifying
349       passwd(1), for example).
350
351   How do I start a process in the background?
352       (contributed by brian d foy)
353
354       There's not a single way to run code in the background so you don't
355       have to wait for it to finish before your program moves on to other
356       tasks. Process management depends on your particular operating system,
357       and many of the techniques are in perlipc.
358
359       Several CPAN modules may be able to help, including "IPC::Open2" or
360       "IPC::Open3", "IPC::Run", "Parallel::Jobs", "Parallel::ForkManager",
361       "POE", "Proc::Background", and "Win32::Process". There are many other
362       modules you might use, so check those namespaces for other options too.
363
364       If you are on a Unix-like system, you might be able to get away with a
365       system call where you put an "&" on the end of the command:
366
367               system("cmd &")
368
369       You can also try using "fork", as described in perlfunc (although this
370       is the same thing that many of the modules will do for you).
371
372       STDIN, STDOUT, and STDERR are shared
373           Both the main process and the backgrounded one (the "child"
374           process) share the same STDIN, STDOUT and STDERR filehandles.  If
375           both try to access them at once, strange things can happen.  You
376           may want to close or reopen these for the child.  You can get
377           around this with "open"ing a pipe (see "open" in perlfunc) but on
378           some systems this means that the child process cannot outlive the
379           parent.
380
381       Signals
382           You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too.
383           SIGCHLD is sent when the backgrounded process finishes.  SIGPIPE is
384           sent when you write to a filehandle whose child process has closed
385           (an untrapped SIGPIPE can cause your program to silently die).
386           This is not an issue with "system("cmd&")".
387
388       Zombies
389           You have to be prepared to "reap" the child process when it
390           finishes.
391
392                   $SIG{CHLD} = sub { wait };
393
394                   $SIG{CHLD} = 'IGNORE';
395
396           You can also use a double fork. You immediately "wait()" for your
397           first child, and the init daemon will "wait()" for your grandchild
398           once it exits.
399
400                   unless ($pid = fork) {
401                       unless (fork) {
402                           exec "what you really wanna do";
403                           die "exec failed!";
404                       }
405                       exit 0;
406                   }
407                   waitpid($pid, 0);
408
409           See "Signals" in perlipc for other examples of code to do this.
410           Zombies are not an issue with "system("prog &")".
411
412   How do I trap control characters/signals?
413       You don't actually "trap" a control character.  Instead, that character
414       generates a signal which is sent to your terminal's currently
415       foregrounded process group, which you then trap in your process.
416       Signals are documented in "Signals" in perlipc and the section on
417       "Signals" in the Camel.
418
419       You can set the values of the %SIG hash to be the functions you want to
420       handle the signal.  After perl catches the signal, it looks in %SIG for
421       a key with the same name as the signal, then calls the subroutine value
422       for that key.
423
424               # as an anonymous subroutine
425
426               $SIG{INT} = sub { syswrite(STDERR, "ouch\n", 5 ) };
427
428               # or a reference to a function
429
430               $SIG{INT} = \&ouch;
431
432               # or the name of the function as a string
433
434               $SIG{INT} = "ouch";
435
436       Perl versions before 5.8 had in its C source code signal handlers which
437       would catch the signal and possibly run a Perl function that you had
438       set in %SIG.  This violated the rules of signal handling at that level
439       causing perl to dump core. Since version 5.8.0, perl looks at %SIG
440       after the signal has been caught, rather than while it is being caught.
441       Previous versions of this answer were incorrect.
442
443   How do I modify the shadow password file on a Unix system?
444       If perl was installed correctly and your shadow library was written
445       properly, the "getpw*()" functions described in perlfunc should in
446       theory provide (read-only) access to entries in the shadow password
447       file.  To change the file, make a new shadow password file (the format
448       varies from system to system--see passwd for specifics) and use
449       pwd_mkdb(8) to install it (see pwd_mkdb for more details).
450
451   How do I set the time and date?
452       Assuming you're running under sufficient permissions, you should be
453       able to set the system-wide date and time by running the date(1)
454       program.  (There is no way to set the time and date on a per-process
455       basis.)  This mechanism will work for Unix, MS-DOS, Windows, and NT;
456       the VMS equivalent is "set time".
457
458       However, if all you want to do is change your time zone, you can
459       probably get away with setting an environment variable:
460
461               $ENV{TZ} = "MST7MDT";              # Unixish
462               $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
463               system "trn comp.lang.perl.misc";
464
465   How can I sleep() or alarm() for under a second?
466       If you want finer granularity than the 1 second that the "sleep()"
467       function provides, the easiest way is to use the "select()" function as
468       documented in "select" in perlfunc.  Try the "Time::HiRes" and the
469       "BSD::Itimer" modules (available from CPAN, and starting from Perl 5.8
470       "Time::HiRes" is part of the standard distribution).
471
472   How can I measure time under a second?
473       (contributed by brian d foy)
474
475       The "Time::HiRes" module (part of the standard distribution as of Perl
476       5.8) measures time with the "gettimeofday()" system call, which returns
477       the time in microseconds since the epoch. If you can't install
478       "Time::HiRes" for older Perls and you are on a Unixish system, you may
479       be able to call gettimeofday(2) directly. See "syscall" in perlfunc.
480
481   How can I do an atexit() or setjmp()/longjmp()? (Exception handling)
482       You can use the "END" block to simulate "atexit()". Each package's
483       "END" block is called when the program or thread ends See perlmod
484       manpage for more details about "END" blocks.
485
486       For example, you can use this to make sure your filter program managed
487       to finish its output without filling up the disk:
488
489               END {
490                       close(STDOUT) || die "stdout close failed: $!";
491               }
492
493       The "END" block isn't called when untrapped signals kill the program,
494       though, so if you use "END" blocks you should also use
495
496               use sigtrap qw(die normal-signals);
497
498       Perl's exception-handling mechanism is its "eval()" operator.  You can
499       use "eval()" as "setjmp" and "die()" as "longjmp". For details of this,
500       see the section on signals, especially the time-out handler for a
501       blocking "flock()" in "Signals" in perlipc or the section on "Signals"
502       in Programming Perl.
503
504       If exception handling is all you're interested in, use one of the many
505       CPAN modules that handle exceptions, such as "Try::Tiny".
506
507       If you want the "atexit()" syntax (and an "rmexit()" as well), try the
508       "AtExit" module available from CPAN.
509
510   Why doesn't my sockets program work under System V (Solaris)?  What does
511       the error message "Protocol not supported" mean?
512       Some Sys-V based systems, notably Solaris 2.X, redefined some of the
513       standard socket constants.  Since these were constant across all
514       architectures, they were often hardwired into perl code.  The proper
515       way to deal with this is to "use Socket" to get the correct values.
516
517       Note that even though SunOS and Solaris are binary compatible, these
518       values are different.  Go figure.
519
520   How can I call my system's unique C functions from Perl?
521       In most cases, you write an external module to do it--see the answer to
522       "Where can I learn about linking C with Perl? [h2xs, xsubpp]".
523       However, if the function is a system call, and your system supports
524       "syscall()", you can use the "syscall" function (documented in
525       perlfunc).
526
527       Remember to check the modules that came with your distribution, and
528       CPAN as well--someone may already have written a module to do it. On
529       Windows, try "Win32::API".  On Macs, try "Mac::Carbon".  If no module
530       has an interface to the C function, you can inline a bit of C in your
531       Perl source with "Inline::C".
532
533   Where do I get the include files to do ioctl() or syscall()?
534       Historically, these would be generated by the "h2ph" tool, part of the
535       standard perl distribution.  This program converts cpp(1) directives in
536       C header files to files containing subroutine definitions, like
537       &SYS_getitimer, which you can use as arguments to your functions.  It
538       doesn't work perfectly, but it usually gets most of the job done.
539       Simple files like errno.h, syscall.h, and socket.h were fine, but the
540       hard ones like ioctl.h nearly always need to be hand-edited.  Here's
541       how to install the *.ph files:
542
543               1.  become super-user
544               2.  cd /usr/include
545               3.  h2ph *.h */*.h
546
547       If your system supports dynamic loading, for reasons of portability and
548       sanity you probably ought to use "h2xs" (also part of the standard perl
549       distribution).  This tool converts C header files to Perl extensions.
550       See perlxstut for how to get started with "h2xs".
551
552       If your system doesn't support dynamic loading, you still probably
553       ought to use "h2xs".  See perlxstut and ExtUtils::MakeMaker for more
554       information (in brief, just use make perl instead of a plain make to
555       rebuild perl with a new static extension).
556
557   Why do setuid perl scripts complain about kernel problems?
558       Some operating systems have bugs in the kernel that make setuid scripts
559       inherently insecure.  Perl gives you a number of options (described in
560       perlsec) to work around such systems.
561
562   How can I open a pipe both to and from a command?
563       The "IPC::Open2" module (part of the standard perl distribution) is an
564       easy-to-use approach that internally uses "pipe()", "fork()", and
565       "exec()" to do the job.  Make sure you read the deadlock warnings in
566       its documentation, though (see IPC::Open2).  See "Bidirectional
567       Communication with Another Process" in perlipc and "Bidirectional
568       Communication with Yourself" in perlipc
569
570       You may also use the "IPC::Open3" module (part of the standard perl
571       distribution), but be warned that it has a different order of arguments
572       from "IPC::Open2" (see IPC::Open3).
573
574   Why can't I get the output of a command with system()?
575       You're confusing the purpose of "system()" and backticks (``).
576       "system()" runs a command and returns exit status information (as a 16
577       bit value: the low 7 bits are the signal the process died from, if any,
578       and the high 8 bits are the actual exit value).  Backticks (``) run a
579       command and return what it sent to STDOUT.
580
581               $exit_status   = system("mail-users");
582               $output_string = `ls`;
583
584   How can I capture STDERR from an external command?
585       There are three basic ways of running external commands:
586
587               system $cmd;            # using system()
588               $output = `$cmd`;               # using backticks (``)
589               open (PIPE, "cmd |");   # using open()
590
591       With "system()", both STDOUT and STDERR will go the same place as the
592       script's STDOUT and STDERR, unless the "system()" command redirects
593       them.  Backticks and "open()" read only the STDOUT of your command.
594
595       You can also use the "open3()" function from "IPC::Open3".  Benjamin
596       Goldberg provides some sample code:
597
598       To capture a program's STDOUT, but discard its STDERR:
599
600               use IPC::Open3;
601               use File::Spec;
602               use Symbol qw(gensym);
603               open(NULL, ">", File::Spec->devnull);
604               my $pid = open3(gensym, \*PH, ">&NULL", "cmd");
605               while( <PH> ) { }
606               waitpid($pid, 0);
607
608       To capture a program's STDERR, but discard its STDOUT:
609
610               use IPC::Open3;
611               use File::Spec;
612               use Symbol qw(gensym);
613               open(NULL, ">", File::Spec->devnull);
614               my $pid = open3(gensym, ">&NULL", \*PH, "cmd");
615               while( <PH> ) { }
616               waitpid($pid, 0);
617
618       To capture a program's STDERR, and let its STDOUT go to our own STDERR:
619
620               use IPC::Open3;
621               use Symbol qw(gensym);
622               my $pid = open3(gensym, ">&STDERR", \*PH, "cmd");
623               while( <PH> ) { }
624               waitpid($pid, 0);
625
626       To read both a command's STDOUT and its STDERR separately, you can
627       redirect them to temp files, let the command run, then read the temp
628       files:
629
630               use IPC::Open3;
631               use Symbol qw(gensym);
632               use IO::File;
633               local *CATCHOUT = IO::File->new_tmpfile;
634               local *CATCHERR = IO::File->new_tmpfile;
635               my $pid = open3(gensym, ">&CATCHOUT", ">&CATCHERR", "cmd");
636               waitpid($pid, 0);
637               seek $_, 0, 0 for \*CATCHOUT, \*CATCHERR;
638               while( <CATCHOUT> ) {}
639               while( <CATCHERR> ) {}
640
641       But there's no real need for both to be tempfiles... the following
642       should work just as well, without deadlocking:
643
644               use IPC::Open3;
645               use Symbol qw(gensym);
646               use IO::File;
647               local *CATCHERR = IO::File->new_tmpfile;
648               my $pid = open3(gensym, \*CATCHOUT, ">&CATCHERR", "cmd");
649               while( <CATCHOUT> ) {}
650               waitpid($pid, 0);
651               seek CATCHERR, 0, 0;
652               while( <CATCHERR> ) {}
653
654       And it'll be faster, too, since we can begin processing the program's
655       stdout immediately, rather than waiting for the program to finish.
656
657       With any of these, you can change file descriptors before the call:
658
659               open(STDOUT, ">logfile");
660               system("ls");
661
662       or you can use Bourne shell file-descriptor redirection:
663
664               $output = `$cmd 2>some_file`;
665               open (PIPE, "cmd 2>some_file |");
666
667       You can also use file-descriptor redirection to make STDERR a duplicate
668       of STDOUT:
669
670               $output = `$cmd 2>&1`;
671               open (PIPE, "cmd 2>&1 |");
672
673       Note that you cannot simply open STDERR to be a dup of STDOUT in your
674       Perl program and avoid calling the shell to do the redirection.  This
675       doesn't work:
676
677               open(STDERR, ">&STDOUT");
678               $alloutput = `cmd args`;  # stderr still escapes
679
680       This fails because the "open()" makes STDERR go to where STDOUT was
681       going at the time of the "open()".  The backticks then make STDOUT go
682       to a string, but don't change STDERR (which still goes to the old
683       STDOUT).
684
685       Note that you must use Bourne shell (sh(1)) redirection syntax in
686       backticks, not csh(1)!  Details on why Perl's "system()" and backtick
687       and pipe opens all use the Bourne shell are in the versus/csh.whynot
688       article in the "Far More Than You Ever Wanted To Know" collection in
689       http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz .  To capture a command's
690       STDERR and STDOUT together:
691
692               $output = `cmd 2>&1`;                       # either with backticks
693               $pid = open(PH, "cmd 2>&1 |");              # or with an open pipe
694               while (<PH>) { }                            #    plus a read
695
696       To capture a command's STDOUT but discard its STDERR:
697
698               $output = `cmd 2>/dev/null`;                # either with backticks
699               $pid = open(PH, "cmd 2>/dev/null |");       # or with an open pipe
700               while (<PH>) { }                            #    plus a read
701
702       To capture a command's STDERR but discard its STDOUT:
703
704               $output = `cmd 2>&1 1>/dev/null`;           # either with backticks
705               $pid = open(PH, "cmd 2>&1 1>/dev/null |");  # or with an open pipe
706               while (<PH>) { }                            #    plus a read
707
708       To exchange a command's STDOUT and STDERR in order to capture the
709       STDERR but leave its STDOUT to come out our old STDERR:
710
711               $output = `cmd 3>&1 1>&2 2>&3 3>&-`;        # either with backticks
712               $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
713               while (<PH>) { }                            #    plus a read
714
715       To read both a command's STDOUT and its STDERR separately, it's easiest
716       to redirect them separately to files, and then read from those files
717       when the program is done:
718
719               system("program args 1>program.stdout 2>program.stderr");
720
721       Ordering is important in all these examples.  That's because the shell
722       processes file descriptor redirections in strictly left to right order.
723
724               system("prog args 1>tmpfile 2>&1");
725               system("prog args 2>&1 1>tmpfile");
726
727       The first command sends both standard out and standard error to the
728       temporary file.  The second command sends only the old standard output
729       there, and the old standard error shows up on the old standard out.
730
731   Why doesn't open() return an error when a pipe open fails?
732       If the second argument to a piped "open()" contains shell
733       metacharacters, perl "fork()"s, then "exec()"s a shell to decode the
734       metacharacters and eventually run the desired program.  If the program
735       couldn't be run, it's the shell that gets the message, not Perl. All
736       your Perl program can find out is whether the shell itself could be
737       successfully started.  You can still capture the shell's STDERR and
738       check it for error messages.  See "How can I capture STDERR from an
739       external command?" elsewhere in this document, or use the "IPC::Open3"
740       module.
741
742       If there are no shell metacharacters in the argument of "open()", Perl
743       runs the command directly, without using the shell, and can correctly
744       report whether the command started.
745
746   What's wrong with using backticks in a void context?
747       Strictly speaking, nothing.  Stylistically speaking, it's not a good
748       way to write maintainable code.  Perl has several operators for running
749       external commands.  Backticks are one; they collect the output from the
750       command for use in your program.  The "system" function is another; it
751       doesn't do this.
752
753       Writing backticks in your program sends a clear message to the readers
754       of your code that you wanted to collect the output of the command.  Why
755       send a clear message that isn't true?
756
757       Consider this line:
758
759               `cat /etc/termcap`;
760
761       You forgot to check $? to see whether the program even ran correctly.
762       Even if you wrote
763
764               print `cat /etc/termcap`;
765
766       this code could and probably should be written as
767
768               system("cat /etc/termcap") == 0
769               or die "cat program failed!";
770
771       which will echo the cat command's output as it is generated, instead of
772       waiting until the program has completed to print it out. It also checks
773       the return value.
774
775       "system" also provides direct control over whether shell wildcard
776       processing may take place, whereas backticks do not.
777
778   How can I call backticks without shell processing?
779       This is a bit tricky.  You can't simply write the command like this:
780
781               @ok = `grep @opts '$search_string' @filenames`;
782
783       As of Perl 5.8.0, you can use "open()" with multiple arguments.  Just
784       like the list forms of "system()" and "exec()", no shell escapes
785       happen.
786
787               open( GREP, "-|", 'grep', @opts, $search_string, @filenames );
788               chomp(@ok = <GREP>);
789               close GREP;
790
791       You can also:
792
793               my @ok = ();
794               if (open(GREP, "-|")) {
795                       while (<GREP>) {
796                               chomp;
797                               push(@ok, $_);
798                       }
799                       close GREP;
800               } else {
801                       exec 'grep', @opts, $search_string, @filenames;
802               }
803
804       Just as with "system()", no shell escapes happen when you "exec()" a
805       list. Further examples of this can be found in "Safe Pipe Opens" in
806       perlipc.
807
808       Note that if you're using Windows, no solution to this vexing issue is
809       even possible.  Even if Perl were to emulate "fork()", you'd still be
810       stuck, because Windows does not have an argc/argv-style API.
811
812   Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on
813       MS-DOS)?
814       This happens only if your perl is compiled to use stdio instead of
815       perlio, which is the default. Some (maybe all?) stdios set error and
816       eof flags that you may need to clear. The "POSIX" module defines
817       "clearerr()" that you can use.  That is the technically correct way to
818       do it.  Here are some less reliable workarounds:
819
820       1.  Try keeping around the seekpointer and go there, like this:
821
822                   $where = tell(LOG);
823                   seek(LOG, $where, 0);
824
825       2.  If that doesn't work, try seeking to a different part of the file
826           and then back.
827
828       3.  If that doesn't work, try seeking to a different part of the file,
829           reading something, and then seeking back.
830
831       4.  If that doesn't work, give up on your stdio package and use
832           sysread.
833
834   How can I convert my shell script to perl?
835       Learn Perl and rewrite it.  Seriously, there's no simple converter.
836       Things that are awkward to do in the shell are easy to do in Perl, and
837       this very awkwardness is what would make a shell->perl converter nigh-
838       on impossible to write.  By rewriting it, you'll think about what
839       you're really trying to do, and hopefully will escape the shell's
840       pipeline datastream paradigm, which while convenient for some matters,
841       causes many inefficiencies.
842
843   Can I use perl to run a telnet or ftp session?
844       Try the "Net::FTP", "TCP::Client", and "Net::Telnet" modules (available
845       from CPAN).  http://www.cpan.org/scripts/netstuff/telnet.emul.shar will
846       also help for emulating the telnet protocol, but "Net::Telnet" is quite
847       probably easier to use.
848
849       If all you want to do is pretend to be telnet but don't need the
850       initial telnet handshaking, then the standard dual-process approach
851       will suffice:
852
853               use IO::Socket;             # new in 5.004
854               $handle = IO::Socket::INET->new('www.perl.com:80')
855                   or die "can't connect to port 80 on www.perl.com: $!";
856               $handle->autoflush(1);
857               if (fork()) {               # XXX: undef means failure
858                   select($handle);
859                   print while <STDIN>;    # everything from stdin to socket
860               } else {
861                   print while <$handle>;  # everything from socket to stdout
862               }
863               close $handle;
864               exit;
865
866   How can I write expect in Perl?
867       Once upon a time, there was a library called chat2.pl (part of the
868       standard perl distribution), which never really got finished.  If you
869       find it somewhere, don't use it.  These days, your best bet is to look
870       at the Expect module available from CPAN, which also requires two other
871       modules from CPAN, "IO::Pty" and "IO::Stty".
872
873   Is there a way to hide perl's command line from programs such as "ps"?
874       First of all note that if you're doing this for security reasons (to
875       avoid people seeing passwords, for example) then you should rewrite
876       your program so that critical information is never given as an
877       argument.  Hiding the arguments won't make your program completely
878       secure.
879
880       To actually alter the visible command line, you can assign to the
881       variable $0 as documented in perlvar.  This won't work on all operating
882       systems, though.  Daemon programs like sendmail place their state
883       there, as in:
884
885               $0 = "orcus [accepting connections]";
886
887   I {changed directory, modified my environment} in a perl script.  How come
888       the change disappeared when I exited the script?  How do I get my
889       changes to be visible?
890       Unix
891           In the strictest sense, it can't be done--the script executes as a
892           different process from the shell it was started from.  Changes to a
893           process are not reflected in its parent--only in any children
894           created after the change.  There is shell magic that may allow you
895           to fake it by "eval()"ing the script's output in your shell; check
896           out the comp.unix.questions FAQ for details.
897
898   How do I close a process's filehandle without waiting for it to complete?
899       Assuming your system supports such things, just send an appropriate
900       signal to the process (see "kill" in perlfunc).  It's common to first
901       send a TERM signal, wait a little bit, and then send a KILL signal to
902       finish it off.
903
904   How do I fork a daemon process?
905       If by daemon process you mean one that's detached (disassociated from
906       its tty), then the following process is reported to work on most
907       Unixish systems.  Non-Unix users should check their Your_OS::Process
908       module for other solutions.
909
910       ·   Open /dev/tty and use the TIOCNOTTY ioctl on it.  See tty for
911           details.  Or better yet, you can just use the "POSIX::setsid()"
912           function, so you don't have to worry about process groups.
913
914       ·   Change directory to /
915
916       ·   Reopen STDIN, STDOUT, and STDERR so they're not connected to the
917           old tty.
918
919       ·   Background yourself like this:
920
921                   fork && exit;
922
923       The "Proc::Daemon" module, available from CPAN, provides a function to
924       perform these actions for you.
925
926   How do I find out if I'm running interactively or not?
927       (contributed by brian d foy)
928
929       This is a difficult question to answer, and the best answer is only a
930       guess.
931
932       What do you really want to know? If you merely want to know if one of
933       your filehandles is connected to a terminal, you can try the "-t" file
934       test:
935
936               if( -t STDOUT ) {
937                       print "I'm connected to a terminal!\n";
938                       }
939
940       However, you might be out of luck if you expect that means there is a
941       real person on the other side. With the "Expect" module, another
942       program can pretend to be a person. The program might even come close
943       to passing the Turing test.
944
945       The "IO::Interactive" module does the best it can to give you an
946       answer. Its "is_interactive" function returns an output filehandle;
947       that filehandle points to standard output if the module thinks the
948       session is interactive. Otherwise, the filehandle is a null handle that
949       simply discards the output:
950
951               use IO::Interactive;
952
953               print { is_interactive } "I might go to standard output!\n";
954
955       This still doesn't guarantee that a real person is answering your
956       prompts or reading your output.
957
958       If you want to know how to handle automated testing for your
959       distribution, you can check the environment. The CPAN Testers, for
960       instance, set the value of "AUTOMATED_TESTING":
961
962               unless( $ENV{AUTOMATED_TESTING} ) {
963                       print "Hello interactive tester!\n";
964                       }
965
966   How do I timeout a slow event?
967       Use the "alarm()" function, probably in conjunction with a signal
968       handler, as documented in "Signals" in perlipc and the section on
969       "Signals" in the Camel.  You may instead use the more flexible
970       "Sys::AlarmCall" module available from CPAN.
971
972       The "alarm()" function is not implemented on all versions of Windows.
973       Check the documentation for your specific version of Perl.
974
975   How do I set CPU limits?
976       (contributed by Xho)
977
978       Use the "BSD::Resource" module from CPAN. As an example:
979
980               use BSD::Resource;
981               setrlimit(RLIMIT_CPU,10,20) or die $!;
982
983       This sets the soft and hard limits to 10 and 20 seconds, respectively.
984       After 10 seconds of time spent running on the CPU (not "wall" time),
985       the process will be sent a signal (XCPU on some systems) which, if not
986       trapped, will cause the process to terminate.  If that signal is
987       trapped, then after 10 more seconds (20 seconds in total) the process
988       will be killed with a non-trappable signal.
989
990       See the "BSD::Resource" and your systems documentation for the gory
991       details.
992
993   How do I avoid zombies on a Unix system?
994       Use the reaper code from "Signals" in perlipc to call "wait()" when a
995       SIGCHLD is received, or else use the double-fork technique described in
996       "How do I start a process in the background?" in perlfaq8.
997
998   How do I use an SQL database?
999       The "DBI" module provides an abstract interface to most database
1000       servers and types, including Oracle, DB2, Sybase, mysql, Postgresql,
1001       ODBC, and flat files.  The DBI module accesses each database type
1002       through a database driver, or DBD.  You can see a complete list of
1003       available drivers on CPAN: http://www.cpan.org/modules/by-module/DBD/ .
1004       You can read more about DBI on http://dbi.perl.org .
1005
1006       Other modules provide more specific access: "Win32::ODBC", "Alzabo",
1007       "iodbc", and others found on CPAN Search: http://search.cpan.org .
1008
1009   How do I make a system() exit on control-C?
1010       You can't.  You need to imitate the "system()" call (see perlipc for
1011       sample code) and then have a signal handler for the INT signal that
1012       passes the signal on to the subprocess.  Or you can check for it:
1013
1014               $rc = system($cmd);
1015               if ($rc & 127) { die "signal death" }
1016
1017   How do I open a file without blocking?
1018       If you're lucky enough to be using a system that supports non-blocking
1019       reads (most Unixish systems do), you need only to use the "O_NDELAY" or
1020       "O_NONBLOCK" flag from the "Fcntl" module in conjunction with
1021       "sysopen()":
1022
1023               use Fcntl;
1024               sysopen(FH, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)
1025                       or die "can't open /foo/somefile: $!":
1026
1027   How do I tell the difference between errors from the shell and perl?
1028       (answer contributed by brian d foy)
1029
1030       When you run a Perl script, something else is running the script for
1031       you, and that something else may output error messages.  The script
1032       might emit its own warnings and error messages.  Most of the time you
1033       cannot tell who said what.
1034
1035       You probably cannot fix the thing that runs perl, but you can change
1036       how perl outputs its warnings by defining a custom warning and die
1037       functions.
1038
1039       Consider this script, which has an error you may not notice
1040       immediately.
1041
1042               #!/usr/locl/bin/perl
1043
1044               print "Hello World\n";
1045
1046       I get an error when I run this from my shell (which happens to be
1047       bash).  That may look like perl forgot it has a "print()" function, but
1048       my shebang line is not the path to perl, so the shell runs the script,
1049       and I get the error.
1050
1051               $ ./test
1052               ./test: line 3: print: command not found
1053
1054       A quick and dirty fix involves a little bit of code, but this may be
1055       all you need to figure out the problem.
1056
1057               #!/usr/bin/perl -w
1058
1059               BEGIN {
1060               $SIG{__WARN__} = sub{ print STDERR "Perl: ", @_; };
1061               $SIG{__DIE__}  = sub{ print STDERR "Perl: ", @_; exit 1};
1062               }
1063
1064               $a = 1 + undef;
1065               $x / 0;
1066               __END__
1067
1068       The perl message comes out with "Perl" in front.  The "BEGIN" block
1069       works at compile time so all of the compilation errors and warnings get
1070       the "Perl:" prefix too.
1071
1072               Perl: Useless use of division (/) in void context at ./test line 9.
1073               Perl: Name "main::a" used only once: possible typo at ./test line 8.
1074               Perl: Name "main::x" used only once: possible typo at ./test line 9.
1075               Perl: Use of uninitialized value in addition (+) at ./test line 8.
1076               Perl: Use of uninitialized value in division (/) at ./test line 9.
1077               Perl: Illegal division by zero at ./test line 9.
1078               Perl: Illegal division by zero at -e line 3.
1079
1080       If I don't see that "Perl:", it's not from perl.
1081
1082       You could also just know all the perl errors, and although there are
1083       some people who may know all of them, you probably don't.  However,
1084       they all should be in the perldiag manpage. If you don't find the error
1085       in there, it probably isn't a perl error.
1086
1087       Looking up every message is not the easiest way, so let perl to do it
1088       for you.  Use the diagnostics pragma with turns perl's normal messages
1089       into longer discussions on the topic.
1090
1091               use diagnostics;
1092
1093       If you don't get a paragraph or two of expanded discussion, it might
1094       not be perl's message.
1095
1096   How do I install a module from CPAN?
1097       (contributed by brian d foy)
1098
1099       The easiest way is to have a module also named CPAN do it for you by
1100       using the "cpan" command the comes with Perl. You can give it a list of
1101       modules to install:
1102
1103               $ cpan IO::Interactive Getopt::Whatever
1104
1105       If you prefer "CPANPLUS", it's just as easy:
1106
1107               $ cpanp i IO::Interactive Getopt::Whatever
1108
1109       If you want to install a distribution from the current directory, you
1110       can tell "CPAN.pm" to install "." (the full stop):
1111
1112               $ cpan .
1113
1114       See the documentation for either of those commands to see what else you
1115       can do.
1116
1117       If you want to try to install a distribution by yourself, resolving all
1118       dependencies on your own, you follow one of two possible build paths.
1119
1120       For distributions that use Makefile.PL:
1121
1122               $ perl Makefile.PL
1123               $ make test install
1124
1125       For distributions that use Build.PL:
1126
1127               $ perl Build.PL
1128               $ ./Build test
1129               $ ./Build install
1130
1131       Some distributions may need to link to libraries or other third-party
1132       code and their build and installation sequences may be more
1133       complicated.  Check any README or INSTALL files that you may find.
1134
1135   What's the difference between require and use?
1136       (contributed by brian d foy)
1137
1138       Perl runs "require" statement at run-time. Once Perl loads, compiles,
1139       and runs the file, it doesn't do anything else. The "use" statement is
1140       the same as a "require" run at compile-time, but Perl also calls the
1141       "import" method for the loaded package. These two are the same:
1142
1143               use MODULE qw(import list);
1144
1145               BEGIN {
1146                       require MODULE;
1147                       MODULE->import(import list);
1148                       }
1149
1150       However, you can suppress the "import" by using an explicit, empty
1151       import list. Both of these still happen at compile-time:
1152
1153               use MODULE ();
1154
1155               BEGIN {
1156                       require MODULE;
1157                       }
1158
1159       Since "use" will also call the "import" method, the actual value for
1160       "MODULE" must be a bareword. That is, "use" cannot load files by name,
1161       although "require" can:
1162
1163               require "$ENV{HOME}/lib/Foo.pm"; # no @INC searching!
1164
1165       See the entry for "use" in perlfunc for more details.
1166
1167   How do I keep my own module/library directory?
1168       When you build modules, tell Perl where to install the modules.
1169
1170       If you want to install modules for your own use, the easiest way might
1171       be "local::lib", which you can download from CPAN. It sets various
1172       installation settings for you, and uses those same settings within your
1173       programs.
1174
1175       If you want more flexibility, you need to configure your CPAN client
1176       for your particular situation.
1177
1178       For "Makefile.PL"-based distributions, use the INSTALL_BASE option when
1179       generating Makefiles:
1180
1181               perl Makefile.PL INSTALL_BASE=/mydir/perl
1182
1183       You can set this in your "CPAN.pm" configuration so modules
1184       automatically install in your private library directory when you use
1185       the CPAN.pm shell:
1186
1187               % cpan
1188               cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
1189               cpan> o conf commit
1190
1191       For "Build.PL"-based distributions, use the --install_base option:
1192
1193               perl Build.PL --install_base /mydir/perl
1194
1195       You can configure "CPAN.pm" to automatically use this option too:
1196
1197               % cpan
1198               cpan> o conf mbuild_arg "--install_base /mydir/perl"
1199               cpan> o conf commit
1200
1201       INSTALL_BASE tells these tools to put your modules into
1202       /mydir/perl/lib/perl5.  See "How do I add a directory to my include
1203       path (@INC) at runtime?" for details on how to run your newly installed
1204       modules.
1205
1206       There is one caveat with INSTALL_BASE, though, since it acts
1207       differently than the PREFIX and LIB settings that older versions of
1208       "ExtUtils::MakeMaker" advocated. INSTALL_BASE does not support
1209       installing modules for multiple versions of Perl or different
1210       architectures under the same directory. You should consider if you
1211       really want that , and if you do, use the older PREFIX and LIB
1212       settings. See the "ExtUtils::Makemaker" documentation for more details.
1213
1214   How do I add the directory my program lives in to the module/library search
1215       path?
1216       (contributed by brian d foy)
1217
1218       If you know the directory already, you can add it to @INC as you would
1219       for any other directory. You might <use lib> if you know the directory
1220       at compile time:
1221
1222               use lib $directory;
1223
1224       The trick in this task is to find the directory. Before your script
1225       does anything else (such as a "chdir"), you can get the current working
1226       directory with the "Cwd" module, which comes with Perl:
1227
1228               BEGIN {
1229                       use Cwd;
1230                       our $directory = cwd;
1231                       }
1232
1233               use lib $directory;
1234
1235       You can do a similar thing with the value of $0, which holds the script
1236       name. That might hold a relative path, but "rel2abs" can turn it into
1237       an absolute path. Once you have the
1238
1239               BEGIN {
1240                       use File::Spec::Functions qw(rel2abs);
1241                       use File::Basename qw(dirname);
1242
1243                       my $path   = rel2abs( $0 );
1244                       our $directory = dirname( $path );
1245                       }
1246
1247               use lib $directory;
1248
1249       The "FindBin" module, which comes with Perl, might work. It finds the
1250       directory of the currently running script and puts it in $Bin, which
1251       you can then use to construct the right library path:
1252
1253               use FindBin qw($Bin);
1254
1255       You can also use "local::lib" to do much of the same thing. Install
1256       modules using "local::lib"'s settings then use the module in your
1257       program:
1258
1259                use local::lib; # sets up a local lib at ~/perl5
1260
1261       See the "local::lib" documentation for more details.
1262
1263   How do I add a directory to my include path (@INC) at runtime?
1264       Here are the suggested ways of modifying your include path, including
1265       environment variables, run-time switches, and in-code statements:
1266
1267       the "PERLLIB" environment variable
1268                   $ export PERLLIB=/path/to/my/dir
1269                   $ perl program.pl
1270
1271       the "PERL5LIB" environment variable
1272                   $ export PERL5LIB=/path/to/my/dir
1273                   $ perl program.pl
1274
1275       the "perl -Idir" command line flag
1276                   $ perl -I/path/to/my/dir program.pl
1277
1278       the "lib" pragma:
1279                   use lib "$ENV{HOME}/myown_perllib";
1280
1281       the "local::lib" module:
1282                   use local::lib;
1283
1284                   use local::lib "~/myown_perllib";
1285
1286       The last is particularly useful because it knows about machine
1287       dependent architectures.  The "lib.pm" pragmatic module was first
1288       included with the 5.002 release of Perl.
1289
1290   What is socket.ph and where do I get it?
1291       It's a Perl 4 style file defining values for system networking
1292       constants.  Sometimes it is built using "h2ph" when Perl is installed,
1293       but other times it is not.  Modern programs "use Socket;" instead.
1294
1296       Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other
1297       authors as noted. All rights reserved.
1298
1299       This documentation is free; you can redistribute it and/or modify it
1300       under the same terms as Perl itself.
1301
1302       Irrespective of its distribution, all code examples in this file are
1303       hereby placed into the public domain.  You are permitted and encouraged
1304       to use this code in your own programs for fun or for profit as you see
1305       fit.  A simple comment in the code giving credit would be courteous but
1306       is not required.
1307
1308
1309
1310perl v5.12.4                      2011-06-07                       PERLFAQ8(1)
Impressum