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