1PERLFAQ8(1) Perl Programmers Reference Guide PERLFAQ8(1)
2
3
4
6 perlfaq8 - System Interaction
7
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 of
20 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 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 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 that
85 should be more efficient than shelling out to stty for each key. It
86 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 systems (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 calls
102 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 to
209 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 the
261 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 select()
313 to determine whether I/O is ready on that device (see "select" in
314 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 various
319 other functions that go bump in the night, finally came up with this:
320
321 sub open_modem {
322 use IPC::Open2;
323 my $stty = `/bin/stty -g`;
324 open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
325 # starting cu hoses /dev/tty's stty settings, even when it has
326 # been opened on a pipe...
327 system("/bin/stty $stty");
328 $_ = <MODEM_IN>;
329 chomp;
330 if ( !m/^Connected/ ) {
331 print STDERR "$0: cu printed `$_' instead of `Connected'\n";
332 }
333 }
334
335 How do I decode encrypted password files?
336 You spend lots and lots of money on dedicated hardware, but this is
337 bound to get you talked about.
338
339 Seriously, you can't if they are Unix password files--the Unix password
340 system employs one-way encryption. It's more like hashing than
341 encryption. The best you can do is check whether something else hashes
342 to the same string. You can't turn a hash back into the original
343 string. Programs like Crack can forcibly (and intelligently) try to
344 guess passwords, but don't (can't) guarantee quick success.
345
346 If you're worried about users selecting bad passwords, you should
347 proactively check when they try to change their password (by modifying
348 passwd(1), for example).
349
350 How do I start a process in the background?
351 (contributed by brian d foy)
352
353 There's not a single way to run code in the background so you don't
354 have to wait for it to finish before your program moves on to other
355 tasks. Process management depends on your particular operating system,
356 and many of the techniques are in perlipc.
357
358 Several CPAN modules may be able to help, including IPC::Open2 or
359 IPC::Open3, IPC::Run, Parallel::Jobs, Parallel::ForkManager, POE,
360 Proc::Background, and Win32::Process. There are many other modules you
361 might use, so check those namespaces for other options too.
362
363 If you are on a unix-like system, you might be able to get away with a
364 system call where you put an "&" on the end of the command:
365
366 system("cmd &")
367
368 You can also try using "fork", as described in perlfunc (although this
369 is the same thing that many of the modules will do for you).
370
371 STDIN, STDOUT, and STDERR are shared
372 Both the main process and the backgrounded one (the "child"
373 process) share the same STDIN, STDOUT and STDERR filehandles. If
374 both try to access them at once, strange things can happen. You
375 may want to close or reopen these for the child. You can get
376 around this with "open"ing a pipe (see "open" in perlfunc) but on
377 some systems this means that the child process cannot outlive the
378 parent.
379
380 Signals
381 You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too.
382 SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is
383 sent when you write to a filehandle whose child process has closed
384 (an untrapped SIGPIPE can cause your program to silently die).
385 This is not an issue with "system("cmd&")".
386
387 Zombies
388 You have to be prepared to "reap" the child process when it
389 finishes.
390
391 $SIG{CHLD} = sub { wait };
392
393 $SIG{CHLD} = 'IGNORE';
394
395 You can also use a double fork. You immediately wait() for your
396 first child, and the init daemon will wait() for your grandchild
397 once it exits.
398
399 unless ($pid = fork) {
400 unless (fork) {
401 exec "what you really wanna do";
402 die "exec failed!";
403 }
404 exit 0;
405 }
406 waitpid($pid, 0);
407
408 See "Signals" in perlipc for other examples of code to do this.
409 Zombies are not an issue with "system("prog &")".
410
411 How do I trap control characters/signals?
412 You don't actually "trap" a control character. Instead, that character
413 generates a signal which is sent to your terminal's currently
414 foregrounded process group, which you then trap in your process.
415 Signals are documented in "Signals" in perlipc and the section on
416 "Signals" in the Camel.
417
418 You can set the values of the %SIG hash to be the functions you want to
419 handle the signal. After perl catches the signal, it looks in %SIG for
420 a key with the same name as the signal, then calls the subroutine value
421 for that key.
422
423 # as an anonymous subroutine
424
425 $SIG{INT} = sub { syswrite(STDERR, "ouch\n", 5 ) };
426
427 # or a reference to a function
428
429 $SIG{INT} = \&ouch;
430
431 # or the name of the function as a string
432
433 $SIG{INT} = "ouch";
434
435 Perl versions before 5.8 had in its C source code signal handlers which
436 would catch the signal and possibly run a Perl function that you had
437 set in %SIG. This violated the rules of signal handling at that level
438 causing perl to dump core. Since version 5.8.0, perl looks at %SIG
439 *after* the signal has been caught, rather than while it is being
440 caught. Previous versions of this answer were incorrect.
441
442 How do I modify the shadow password file on a Unix system?
443 If perl was installed correctly and your shadow library was written
444 properly, the getpw*() functions described in perlfunc should in theory
445 provide (read-only) access to entries in the shadow password file. To
446 change the file, make a new shadow password file (the format varies
447 from system to system--see passwd for specifics) and use pwd_mkdb(8) to
448 install it (see pwd_mkdb for more details).
449
450 How do I set the time and date?
451 Assuming you're running under sufficient permissions, you should be
452 able to set the system-wide date and time by running the date(1)
453 program. (There is no way to set the time and date on a per-process
454 basis.) This mechanism will work for Unix, MS-DOS, Windows, and NT;
455 the VMS equivalent is "set time".
456
457 However, if all you want to do is change your time zone, you can
458 probably get away with setting an environment variable:
459
460 $ENV{TZ} = "MST7MDT"; # unixish
461 $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
462 system "trn comp.lang.perl.misc";
463
464 How can I sleep() or alarm() for under a second?
465 If you want finer granularity than the 1 second that the "sleep()"
466 function provides, the easiest way is to use the "select()" function as
467 documented in "select" in perlfunc. Try the "Time::HiRes" and the
468 "BSD::Itimer" modules (available from CPAN, and starting from Perl 5.8
469 "Time::HiRes" is part of the standard distribution).
470
471 How can I measure time under a second?
472 (contributed by brian d foy)
473
474 The "Time::HiRes" module (part of the standard distribution as of Perl
475 5.8) measures time with the "gettimeofday()" system call, which returns
476 the time in microseconds since the epoch. If you can't install
477 "Time::HiRes" for older Perls and you are on a Unixish system, you may
478 be able to call gettimeofday(2) directly. See "syscall" in perlfunc.
479
480 How can I do an atexit() or setjmp()/longjmp()? (Exception handling)
481 Release 5 of Perl added the END block, which can be used to simulate
482 atexit(). Each package's END block is called when the program or
483 thread ends (see perlmod manpage for more details).
484
485 For example, you can use this to make sure your filter program managed
486 to finish its output without filling up the disk:
487
488 END {
489 close(STDOUT) || die "stdout close failed: $!";
490 }
491
492 The END block isn't called when untrapped signals kill the program,
493 though, so if you use END blocks you should also use
494
495 use sigtrap qw(die normal-signals);
496
497 Perl's exception-handling mechanism is its eval() operator. You can
498 use eval() as setjmp and die() as longjmp. For details of this, see
499 the section on signals, especially the time-out handler for a blocking
500 flock() in "Signals" in perlipc or the section on "Signals" in the
501 Camel Book.
502
503 If exception handling is all you're interested in, try the
504 exceptions.pl library (part of the standard perl distribution).
505
506 If you want the atexit() syntax (and an rmexit() as well), try the
507 AtExit module available from CPAN.
508
509 Why doesn't my sockets program work under System V (Solaris)? What does
510 the error message "Protocol not supported" mean?
511 Some Sys-V based systems, notably Solaris 2.X, redefined some of the
512 standard socket constants. Since these were constant across all
513 architectures, they were often hardwired into perl code. The proper
514 way to deal with this is to "use Socket" to get the correct values.
515
516 Note that even though SunOS and Solaris are binary compatible, these
517 values are different. Go figure.
518
519 How can I call my system's unique C functions from Perl?
520 In most cases, you write an external module to do it--see the answer to
521 "Where can I learn about linking C with Perl? [h2xs, xsubpp]".
522 However, if the function is a system call, and your system supports
523 syscall(), you can use the syscall function (documented in perlfunc).
524
525 Remember to check the modules that came with your distribution, and
526 CPAN as well--someone may already have written a module to do it. On
527 Windows, try Win32::API. On Macs, try Mac::Carbon. If no module has
528 an interface to the C function, you can inline a bit of C in your Perl
529 source with Inline::C.
530
531 Where do I get the include files to do ioctl() or syscall()?
532 Historically, these would be generated by the h2ph tool, part of the
533 standard perl distribution. This program converts cpp(1) directives in
534 C header files to files containing subroutine definitions, like
535 &SYS_getitimer, which you can use as arguments to your functions. It
536 doesn't work perfectly, but it usually gets most of the job done.
537 Simple files like errno.h, syscall.h, and socket.h were fine, but the
538 hard ones like ioctl.h nearly always need to hand-edited. Here's how
539 to install the *.ph files:
540
541 1. become super-user
542 2. cd /usr/include
543 3. h2ph *.h */*.h
544
545 If your system supports dynamic loading, for reasons of portability and
546 sanity you probably ought to use h2xs (also part of the standard perl
547 distribution). This tool converts C header files to Perl extensions.
548 See perlxstut for how to get started with h2xs.
549
550 If your system doesn't support dynamic loading, you still probably
551 ought to use h2xs. See perlxstut and ExtUtils::MakeMaker for more
552 information (in brief, just use make perl instead of a plain make to
553 rebuild perl with a new static extension).
554
555 Why do setuid perl scripts complain about kernel problems?
556 Some operating systems have bugs in the kernel that make setuid scripts
557 inherently insecure. Perl gives you a number of options (described in
558 perlsec) to work around such systems.
559
560 How can I open a pipe both to and from a command?
561 The IPC::Open2 module (part of the standard perl distribution) is an
562 easy-to-use approach that internally uses pipe(), fork(), and exec() to
563 do the job. Make sure you read the deadlock warnings in its
564 documentation, though (see IPC::Open2). See "Bidirectional
565 Communication with Another Process" in perlipc and "Bidirectional
566 Communication with Yourself" in perlipc
567
568 You may also use the IPC::Open3 module (part of the standard perl
569 distribution), but be warned that it has a different order of arguments
570 from IPC::Open2 (see IPC::Open3).
571
572 Why can't I get the output of a command with system()?
573 You're confusing the purpose of system() and backticks (``). system()
574 runs a command and returns exit status information (as a 16 bit value:
575 the low 7 bits are the signal the process died from, if any, and the
576 high 8 bits are the actual exit value). Backticks (``) run a command
577 and return what it sent to STDOUT.
578
579 $exit_status = system("mail-users");
580 $output_string = `ls`;
581
582 How can I capture STDERR from an external command?
583 There are three basic ways of running external commands:
584
585 system $cmd; # using system()
586 $output = `$cmd`; # using backticks (``)
587 open (PIPE, "cmd |"); # using open()
588
589 With system(), both STDOUT and STDERR will go the same place as the
590 script's STDOUT and STDERR, unless the system() command redirects them.
591 Backticks and open() read only the STDOUT of your command.
592
593 You can also use the open3() function from IPC::Open3. Benjamin
594 Goldberg provides some sample code:
595
596 To capture a program's STDOUT, but discard its STDERR:
597
598 use IPC::Open3;
599 use File::Spec;
600 use Symbol qw(gensym);
601 open(NULL, ">", File::Spec->devnull);
602 my $pid = open3(gensym, \*PH, ">&NULL", "cmd");
603 while( <PH> ) { }
604 waitpid($pid, 0);
605
606 To capture a program's STDERR, but discard its STDOUT:
607
608 use IPC::Open3;
609 use File::Spec;
610 use Symbol qw(gensym);
611 open(NULL, ">", File::Spec->devnull);
612 my $pid = open3(gensym, ">&NULL", \*PH, "cmd");
613 while( <PH> ) { }
614 waitpid($pid, 0);
615
616 To capture a program's STDERR, and let its STDOUT go to our own STDERR:
617
618 use IPC::Open3;
619 use Symbol qw(gensym);
620 my $pid = open3(gensym, ">&STDERR", \*PH, "cmd");
621 while( <PH> ) { }
622 waitpid($pid, 0);
623
624 To read both a command's STDOUT and its STDERR separately, you can
625 redirect them to temp files, let the command run, then read the temp
626 files:
627
628 use IPC::Open3;
629 use Symbol qw(gensym);
630 use IO::File;
631 local *CATCHOUT = IO::File->new_tmpfile;
632 local *CATCHERR = IO::File->new_tmpfile;
633 my $pid = open3(gensym, ">&CATCHOUT", ">&CATCHERR", "cmd");
634 waitpid($pid, 0);
635 seek $_, 0, 0 for \*CATCHOUT, \*CATCHERR;
636 while( <CATCHOUT> ) {}
637 while( <CATCHERR> ) {}
638
639 But there's no real need for *both* to be tempfiles... the following
640 should work just as well, without deadlocking:
641
642 use IPC::Open3;
643 use Symbol qw(gensym);
644 use IO::File;
645 local *CATCHERR = IO::File->new_tmpfile;
646 my $pid = open3(gensym, \*CATCHOUT, ">&CATCHERR", "cmd");
647 while( <CATCHOUT> ) {}
648 waitpid($pid, 0);
649 seek CATCHERR, 0, 0;
650 while( <CATCHERR> ) {}
651
652 And it'll be faster, too, since we can begin processing the program's
653 stdout immediately, rather than waiting for the program to finish.
654
655 With any of these, you can change file descriptors before the call:
656
657 open(STDOUT, ">logfile");
658 system("ls");
659
660 or you can use Bourne shell file-descriptor redirection:
661
662 $output = `$cmd 2>some_file`;
663 open (PIPE, "cmd 2>some_file |");
664
665 You can also use file-descriptor redirection to make STDERR a duplicate
666 of STDOUT:
667
668 $output = `$cmd 2>&1`;
669 open (PIPE, "cmd 2>&1 |");
670
671 Note that you cannot simply open STDERR to be a dup of STDOUT in your
672 Perl program and avoid calling the shell to do the redirection. This
673 doesn't work:
674
675 open(STDERR, ">&STDOUT");
676 $alloutput = `cmd args`; # stderr still escapes
677
678 This fails because the open() makes STDERR go to where STDOUT was going
679 at the time of the open(). The backticks then make STDOUT go to a
680 string, but don't change STDERR (which still goes to the old STDOUT).
681
682 Note that you must use Bourne shell (sh(1)) redirection syntax in
683 backticks, not csh(1)! Details on why Perl's system() and backtick and
684 pipe opens all use the Bourne shell are in the versus/csh.whynot
685 article in the "Far More Than You Ever Wanted To Know" collection in
686 http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz . To capture a command's
687 STDERR and STDOUT together:
688
689 $output = `cmd 2>&1`; # either with backticks
690 $pid = open(PH, "cmd 2>&1 |"); # or with an open pipe
691 while (<PH>) { } # plus a read
692
693 To capture a command's STDOUT but discard its STDERR:
694
695 $output = `cmd 2>/dev/null`; # either with backticks
696 $pid = open(PH, "cmd 2>/dev/null |"); # or with an open pipe
697 while (<PH>) { } # plus a read
698
699 To capture a command's STDERR but discard its STDOUT:
700
701 $output = `cmd 2>&1 1>/dev/null`; # either with backticks
702 $pid = open(PH, "cmd 2>&1 1>/dev/null |"); # or with an open pipe
703 while (<PH>) { } # plus a read
704
705 To exchange a command's STDOUT and STDERR in order to capture the
706 STDERR but leave its STDOUT to come out our old STDERR:
707
708 $output = `cmd 3>&1 1>&2 2>&3 3>&-`; # either with backticks
709 $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
710 while (<PH>) { } # plus a read
711
712 To read both a command's STDOUT and its STDERR separately, it's easiest
713 to redirect them separately to files, and then read from those files
714 when the program is done:
715
716 system("program args 1>program.stdout 2>program.stderr");
717
718 Ordering is important in all these examples. That's because the shell
719 processes file descriptor redirections in strictly left to right order.
720
721 system("prog args 1>tmpfile 2>&1");
722 system("prog args 2>&1 1>tmpfile");
723
724 The first command sends both standard out and standard error to the
725 temporary file. The second command sends only the old standard output
726 there, and the old standard error shows up on the old standard out.
727
728 Why doesn't open() return an error when a pipe open fails?
729 If the second argument to a piped open() contains shell metacharacters,
730 perl fork()s, then exec()s a shell to decode the metacharacters and
731 eventually run the desired program. If the program couldn't be run,
732 it's the shell that gets the message, not Perl. All your Perl program
733 can find out is whether the shell itself could be successfully started.
734 You can still capture the shell's STDERR and check it for error
735 messages. See "How can I capture STDERR from an external command?"
736 elsewhere in this document, or use the IPC::Open3 module.
737
738 If there are no shell metacharacters in the argument of open(), Perl
739 runs the command directly, without using the shell, and can correctly
740 report whether the command started.
741
742 What's wrong with using backticks in a void context?
743 Strictly speaking, nothing. Stylistically speaking, it's not a good
744 way to write maintainable code. Perl has several operators for running
745 external commands. Backticks are one; they collect the output from the
746 command for use in your program. The "system" function is another; it
747 doesn't do this.
748
749 Writing backticks in your program sends a clear message to the readers
750 of your code that you wanted to collect the output of the command. Why
751 send a clear message that isn't true?
752
753 Consider this line:
754
755 `cat /etc/termcap`;
756
757 You forgot to check $? to see whether the program even ran correctly.
758 Even if you wrote
759
760 print `cat /etc/termcap`;
761
762 this code could and probably should be written as
763
764 system("cat /etc/termcap") == 0
765 or die "cat program failed!";
766
767 which will echo the cat command's output as it is generated, instead of
768 waiting until the program has completed to print it out. It also checks
769 the return value.
770
771 "system" also provides direct control over whether shell wildcard
772 processing may take place, whereas backticks do not.
773
774 How can I call backticks without shell processing?
775 This is a bit tricky. You can't simply write the command like this:
776
777 @ok = `grep @opts '$search_string' @filenames`;
778
779 As of Perl 5.8.0, you can use "open()" with multiple arguments. Just
780 like the list forms of "system()" and "exec()", no shell escapes
781 happen.
782
783 open( GREP, "-|", 'grep', @opts, $search_string, @filenames );
784 chomp(@ok = <GREP>);
785 close GREP;
786
787 You can also:
788
789 my @ok = ();
790 if (open(GREP, "-|")) {
791 while (<GREP>) {
792 chomp;
793 push(@ok, $_);
794 }
795 close GREP;
796 } else {
797 exec 'grep', @opts, $search_string, @filenames;
798 }
799
800 Just as with "system()", no shell escapes happen when you "exec()" a
801 list. Further examples of this can be found in "Safe Pipe Opens" in
802 perlipc.
803
804 Note that if you're using Windows, no solution to this vexing issue is
805 even possible. Even if Perl were to emulate "fork()", you'd still be
806 stuck, because Windows does not have an argc/argv-style API.
807
808 Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on
809 MS-DOS)?
810 Some stdio's set error and eof flags that need clearing. The POSIX
811 module defines clearerr() that you can use. That is the technically
812 correct way to do it. Here are some less reliable workarounds:
813
814 1. Try keeping around the seekpointer and go there, like this:
815
816 $where = tell(LOG);
817 seek(LOG, $where, 0);
818
819 2. If that doesn't work, try seeking to a different part of the file
820 and then back.
821
822 3. If that doesn't work, try seeking to a different part of the file,
823 reading something, and then seeking back.
824
825 4. If that doesn't work, give up on your stdio package and use
826 sysread.
827
828 How can I convert my shell script to perl?
829 Learn Perl and rewrite it. Seriously, there's no simple converter.
830 Things that are awkward to do in the shell are easy to do in Perl, and
831 this very awkwardness is what would make a shell->perl converter nigh-
832 on impossible to write. By rewriting it, you'll think about what
833 you're really trying to do, and hopefully will escape the shell's
834 pipeline datastream paradigm, which while convenient for some matters,
835 causes many inefficiencies.
836
837 Can I use perl to run a telnet or ftp session?
838 Try the Net::FTP, TCP::Client, and Net::Telnet modules (available from
839 CPAN). http://www.cpan.org/scripts/netstuff/telnet.emul.shar will also
840 help for emulating the telnet protocol, but Net::Telnet is quite
841 probably easier to use..
842
843 If all you want to do is pretend to be telnet but don't need the
844 initial telnet handshaking, then the standard dual-process approach
845 will suffice:
846
847 use IO::Socket; # new in 5.004
848 $handle = IO::Socket::INET->new('www.perl.com:80')
849 or die "can't connect to port 80 on www.perl.com: $!";
850 $handle->autoflush(1);
851 if (fork()) { # XXX: undef means failure
852 select($handle);
853 print while <STDIN>; # everything from stdin to socket
854 } else {
855 print while <$handle>; # everything from socket to stdout
856 }
857 close $handle;
858 exit;
859
860 How can I write expect in Perl?
861 Once upon a time, there was a library called chat2.pl (part of the
862 standard perl distribution), which never really got finished. If you
863 find it somewhere, don't use it. These days, your best bet is to look
864 at the Expect module available from CPAN, which also requires two other
865 modules from CPAN, IO::Pty and IO::Stty.
866
867 Is there a way to hide perl's command line from programs such as "ps"?
868 First of all note that if you're doing this for security reasons (to
869 avoid people seeing passwords, for example) then you should rewrite
870 your program so that critical information is never given as an
871 argument. Hiding the arguments won't make your program completely
872 secure.
873
874 To actually alter the visible command line, you can assign to the
875 variable $0 as documented in perlvar. This won't work on all operating
876 systems, though. Daemon programs like sendmail place their state
877 there, as in:
878
879 $0 = "orcus [accepting connections]";
880
881 I {changed directory, modified my environment} in a perl script. How come
882 the change disappeared when I exited the script? How do I get my
883 changes to be visible?
884 Unix
885 In the strictest sense, it can't be done--the script executes as a
886 different process from the shell it was started from. Changes to a
887 process are not reflected in its parent--only in any children
888 created after the change. There is shell magic that may allow you
889 to fake it by eval()ing the script's output in your shell; check
890 out the comp.unix.questions FAQ for details.
891
892 How do I close a process's filehandle without waiting for it to complete?
893 Assuming your system supports such things, just send an appropriate
894 signal to the process (see "kill" in perlfunc). It's common to first
895 send a TERM signal, wait a little bit, and then send a KILL signal to
896 finish it off.
897
898 How do I fork a daemon process?
899 If by daemon process you mean one that's detached (disassociated from
900 its tty), then the following process is reported to work on most
901 Unixish systems. Non-Unix users should check their Your_OS::Process
902 module for other solutions.
903
904 · Open /dev/tty and use the TIOCNOTTY ioctl on it. See tty for
905 details. Or better yet, you can just use the POSIX::setsid()
906 function, so you don't have to worry about process groups.
907
908 · Change directory to /
909
910 · Reopen STDIN, STDOUT, and STDERR so they're not connected to the
911 old tty.
912
913 · Background yourself like this:
914
915 fork && exit;
916
917 The Proc::Daemon module, available from CPAN, provides a function to
918 perform these actions for you.
919
920 How do I find out if I'm running interactively or not?
921 Good question. Sometimes "-t STDIN" and "-t STDOUT" can give clues,
922 sometimes not.
923
924 if (-t STDIN && -t STDOUT) {
925 print "Now what? ";
926 }
927
928 On POSIX systems, you can test whether your own process group matches
929 the current process group of your controlling terminal as follows:
930
931 use POSIX qw/getpgrp tcgetpgrp/;
932
933 # Some POSIX systems, such as Linux, can be
934 # without a /dev/tty at boot time.
935 if (!open(TTY, "/dev/tty")) {
936 print "no tty\n";
937 } else {
938 $tpgrp = tcgetpgrp(fileno(*TTY));
939 $pgrp = getpgrp();
940 if ($tpgrp == $pgrp) {
941 print "foreground\n";
942 } else {
943 print "background\n";
944 }
945 }
946
947 How do I timeout a slow event?
948 Use the alarm() function, probably in conjunction with a signal
949 handler, as documented in "Signals" in perlipc and the section on
950 "Signals" in the Camel. You may instead use the more flexible
951 Sys::AlarmCall module available from CPAN.
952
953 The alarm() function is not implemented on all versions of Windows.
954 Check the documentation for your specific version of Perl.
955
956 How do I set CPU limits?
957 (contributed by Xho)
958
959 Use the "BSD::Resource" module from CPAN. As an example:
960
961 use BSD::Resource;
962 setrlimit(RLIMIT_CPU,10,20) or die $!;
963
964 This sets the soft and hard limits to 10 and 20 seconds, respectively.
965 After 10 seconds of time spent running on the CPU (not "wall" time),
966 the process will be sent a signal (XCPU on some systems) which, if not
967 trapped, will cause the process to terminate. If that signal is
968 trapped, then after 10 more seconds (20 seconds in total) the process
969 will be killed with a non-trappable signal.
970
971 See the "BSD::Resource" and your systems documentation for the gory
972 details.
973
974 How do I avoid zombies on a Unix system?
975 Use the reaper code from "Signals" in perlipc to call wait() when a
976 SIGCHLD is received, or else use the double-fork technique described in
977 "How do I start a process in the background?" in perlfaq8.
978
979 How do I use an SQL database?
980 The DBI module provides an abstract interface to most database servers
981 and types, including Oracle, DB2, Sybase, mysql, Postgresql, ODBC, and
982 flat files. The DBI module accesses each database type through a
983 database driver, or DBD. You can see a complete list of available
984 drivers on CPAN: http://www.cpan.org/modules/by-module/DBD/ . You can
985 read more about DBI on http://dbi.perl.org .
986
987 Other modules provide more specific access: Win32::ODBC, Alzabo, iodbc,
988 and others found on CPAN Search: http://search.cpan.org .
989
990 How do I make a system() exit on control-C?
991 You can't. You need to imitate the system() call (see perlipc for
992 sample code) and then have a signal handler for the INT signal that
993 passes the signal on to the subprocess. Or you can check for it:
994
995 $rc = system($cmd);
996 if ($rc & 127) { die "signal death" }
997
998 How do I open a file without blocking?
999 If you're lucky enough to be using a system that supports non-blocking
1000 reads (most Unixish systems do), you need only to use the O_NDELAY or
1001 O_NONBLOCK flag from the Fcntl module in conjunction with sysopen():
1002
1003 use Fcntl;
1004 sysopen(FH, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)
1005 or die "can't open /foo/somefile: $!":
1006
1007 How do I tell the difference between errors from the shell and perl?
1008 (answer contributed by brian d foy)
1009
1010 When you run a Perl script, something else is running the script for
1011 you, and that something else may output error messages. The script
1012 might emit its own warnings and error messages. Most of the time you
1013 cannot tell who said what.
1014
1015 You probably cannot fix the thing that runs perl, but you can change
1016 how perl outputs its warnings by defining a custom warning and die
1017 functions.
1018
1019 Consider this script, which has an error you may not notice
1020 immediately.
1021
1022 #!/usr/locl/bin/perl
1023
1024 print "Hello World\n";
1025
1026 I get an error when I run this from my shell (which happens to be
1027 bash). That may look like perl forgot it has a print() function, but
1028 my shebang line is not the path to perl, so the shell runs the script,
1029 and I get the error.
1030
1031 $ ./test
1032 ./test: line 3: print: command not found
1033
1034 A quick and dirty fix involves a little bit of code, but this may be
1035 all you need to figure out the problem.
1036
1037 #!/usr/bin/perl -w
1038
1039 BEGIN {
1040 $SIG{__WARN__} = sub{ print STDERR "Perl: ", @_; };
1041 $SIG{__DIE__} = sub{ print STDERR "Perl: ", @_; exit 1};
1042 }
1043
1044 $a = 1 + undef;
1045 $x / 0;
1046 __END__
1047
1048 The perl message comes out with "Perl" in front. The BEGIN block works
1049 at compile time so all of the compilation errors and warnings get the
1050 "Perl:" prefix too.
1051
1052 Perl: Useless use of division (/) in void context at ./test line 9.
1053 Perl: Name "main::a" used only once: possible typo at ./test line 8.
1054 Perl: Name "main::x" used only once: possible typo at ./test line 9.
1055 Perl: Use of uninitialized value in addition (+) at ./test line 8.
1056 Perl: Use of uninitialized value in division (/) at ./test line 9.
1057 Perl: Illegal division by zero at ./test line 9.
1058 Perl: Illegal division by zero at -e line 3.
1059
1060 If I don't see that "Perl:", it's not from perl.
1061
1062 You could also just know all the perl errors, and although there are
1063 some people who may know all of them, you probably don't. However,
1064 they all should be in the perldiag manpage. If you don't find the error
1065 in there, it probably isn't a perl error.
1066
1067 Looking up every message is not the easiest way, so let perl to do it
1068 for you. Use the diagnostics pragma with turns perl's normal messages
1069 into longer discussions on the topic.
1070
1071 use diagnostics;
1072
1073 If you don't get a paragraph or two of expanded discussion, it might
1074 not be perl's message.
1075
1076 How do I install a module from CPAN?
1077 The easiest way is to have a module also named CPAN do it for you.
1078 This module comes with perl version 5.004 and later.
1079
1080 $ perl -MCPAN -e shell
1081
1082 cpan shell -- CPAN exploration and modules installation (v1.59_54)
1083 ReadLine support enabled
1084
1085 cpan> install Some::Module
1086
1087 To manually install the CPAN module, or any well-behaved CPAN module
1088 for that matter, follow these steps:
1089
1090 1. Unpack the source into a temporary area.
1091
1092 2.
1093 perl Makefile.PL
1094
1095 3.
1096 make
1097
1098 4.
1099 make test
1100
1101 5.
1102 make install
1103
1104 If your version of perl is compiled without dynamic loading, then you
1105 just need to replace step 3 (make) with make perl and you will get a
1106 new perl binary with your extension linked in.
1107
1108 See ExtUtils::MakeMaker for more details on building extensions. See
1109 also the next question, "What's the difference between require and
1110 use?".
1111
1112 What's the difference between require and use?
1113 (contributed by brian d foy)
1114
1115 Perl runs "require" statement at run-time. Once Perl loads, compiles,
1116 and runs the file, it doesn't do anything else. The "use" statement is
1117 the same as a "require" run at compile-time, but Perl also calls the
1118 "import" method for the loaded package. These two are the same:
1119
1120 use MODULE qw(import list);
1121
1122 BEGIN {
1123 require MODULE;
1124 MODULE->import(import list);
1125 }
1126
1127 However, you can suppress the "import" by using an explicit, empty
1128 import list. Both of these still happen at compile-time:
1129
1130 use MODULE ();
1131
1132 BEGIN {
1133 require MODULE;
1134 }
1135
1136 Since "use" will also call the "import" method, the actual value for
1137 "MODULE" must be a bareword. That is, "use" cannot load files by name,
1138 although "require" can:
1139
1140 require "$ENV{HOME}/lib/Foo.pm"; # no @INC searching!
1141
1142 See the entry for "use" in perlfunc for more details.
1143
1144 How do I keep my own module/library directory?
1145 When you build modules, tell Perl where to install the modules.
1146
1147 For "Makefile.PL"-based distributions, use the INSTALL_BASE option when
1148 generating Makefiles:
1149
1150 perl Makefile.PL INSTALL_BASE=/mydir/perl
1151
1152 You can set this in your CPAN.pm configuration so modules automatically
1153 install in your private library directory when you use the CPAN.pm
1154 shell:
1155
1156 % cpan
1157 cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
1158 cpan> o conf commit
1159
1160 For "Build.PL"-based distributions, use the --install_base option:
1161
1162 perl Build.PL --install_base /mydir/perl
1163
1164 You can configure CPAN.pm to automatically use this option too:
1165
1166 % cpan
1167 cpan> o conf mbuild_arg --install_base /mydir/perl
1168 cpan> o conf commit
1169
1170 INSTALL_BASE tells these tools to put your modules into
1171 /mydir/perl/lib/perl5. See "How do I add a directory to my include
1172 path (@INC) at runtime?" for details on how to run your newly installed
1173 moudles.
1174
1175 There is one caveat with INSTALL_BASE, though, since it acts
1176 differently than the PREFIX and LIB settings that older versions of
1177 ExtUtils::MakeMaker advocated. INSTALL_BASE does not support installing
1178 modules for multiple versions of Perl or different architectures under
1179 the same directory. You should consider if you really want that , and
1180 if you do, use the older PREFIX and LIB settings. See the
1181 ExtUtils::Makemaker documentation for more details.
1182
1183 How do I add the directory my program lives in to the module/library search
1184 path?
1185 (contributed by brian d foy)
1186
1187 If you know the directory already, you can add it to @INC as you would
1188 for any other directory. You might <use lib> if you know the directory
1189 at compile time:
1190
1191 use lib $directory;
1192
1193 The trick in this task is to find the directory. Before your script
1194 does anything else (such as a "chdir"), you can get the current working
1195 directory with the "Cwd" module, which comes with Perl:
1196
1197 BEGIN {
1198 use Cwd;
1199 our $directory = cwd;
1200 }
1201
1202 use lib $directory;
1203
1204 You can do a similar thing with the value of $0, which holds the script
1205 name. That might hold a relative path, but "rel2abs" can turn it into
1206 an absolute path. Once you have the
1207
1208 BEGIN {
1209 use File::Spec::Functions qw(rel2abs);
1210 use File::Basename qw(dirname);
1211
1212 my $path = rel2abs( $0 );
1213 our $directory = dirname( $path );
1214 }
1215
1216 use lib $directory;
1217
1218 The "FindBin" module, which comes with Perl, might work. It finds the
1219 directory of the currently running script and puts it in $Bin, which
1220 you can then use to construct the right library path:
1221
1222 use FindBin qw($Bin);
1223
1224 How do I add a directory to my include path (@INC) at runtime?
1225 Here are the suggested ways of modifying your include path, including
1226 environment variables, run-time switches, and in-code statements:
1227
1228 the PERLLIB environment variable
1229 $ export PERLLIB=/path/to/my/dir
1230 $ perl program.pl
1231
1232 the PERL5LIB environment variable
1233 $ export PERL5LIB=/path/to/my/dir
1234 $ perl program.pl
1235
1236 the perl -Idir command line flag
1237 $ perl -I/path/to/my/dir program.pl
1238
1239 the use lib pragma:
1240 use lib "$ENV{HOME}/myown_perllib";
1241
1242 The last is particularly useful because it knows about machine
1243 dependent architectures. The lib.pm pragmatic module was first
1244 included with the 5.002 release of Perl.
1245
1246 What is socket.ph and where do I get it?
1247 It's a Perl 4 style file defining values for system networking
1248 constants. Sometimes it is built using h2ph when Perl is installed,
1249 but other times it is not. Modern programs "use Socket;" instead.
1250
1252 Revision: $Revision$
1253
1254 Date: $Date$
1255
1256 See perlfaq for source control details and availability.
1257
1259 Copyright (c) 1997-2009 Tom Christiansen, Nathan Torkington, and other
1260 authors as noted. All rights reserved.
1261
1262 This documentation is free; you can redistribute it and/or modify it
1263 under the same terms as Perl itself.
1264
1265 Irrespective of its distribution, all code examples in this file are
1266 hereby placed into the public domain. You are permitted and encouraged
1267 to use this code in your own programs for fun or for profit as you see
1268 fit. A simple comment in the code giving credit would be courteous but
1269 is not required.
1270
1271
1272
1273perl v5.10.1 2009-08-15 PERLFAQ8(1)