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