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