1perlfaq8(3) User Contributed Perl Documentation perlfaq8(3)
2
3
4
6 perlfaq8 - System Interaction
7
9 version 5.20230812
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 the
269 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 select()
321 to determine whether I/O is ready on that device (see "select" in
322 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 "END"
491 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 use
507 eval() as "setjmp" and die() as "longjmp". For details of this, see the
508 section on signals, especially the time-out handler for a blocking
509 flock() in "Signals" in perlipc or the section on "Signals" in
510 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 perlfunc).
533
534 Remember to check the modules that came with your distribution, and
535 CPAN as well--someone may already have written a module to do it. On
536 Windows, try Win32::API. On Macs, try Mac::Carbon. If no module has an
537 interface to the C function, you can inline a bit of C in your Perl
538 source with Inline::C.
539
540 Where do I get the include files to do ioctl() or syscall()?
541 Historically, these would be generated by the h2ph tool, part of the
542 standard perl distribution. This program converts cpp(1) directives in
543 C header files to files containing subroutine definitions, like
544 SYS_getitimer(), which you can use as arguments to your functions. It
545 doesn't work perfectly, but it usually gets most of the job done.
546 Simple files like errno.h, syscall.h, and socket.h were fine, but the
547 hard ones like ioctl.h nearly always need to be hand-edited. Here's
548 how to install the *.ph files:
549
550 1. Become the super-user
551 2. cd /usr/include
552 3. h2ph *.h */*.h
553
554 If your system supports dynamic loading, for reasons of portability and
555 sanity you probably ought to use h2xs (also part of the standard perl
556 distribution). This tool converts C header files to Perl extensions.
557 See perlxstut for how to get started with h2xs.
558
559 If your system doesn't support dynamic loading, you still probably
560 ought to use h2xs. See perlxstut and ExtUtils::MakeMaker for more
561 information (in brief, just use make perl instead of a plain make to
562 rebuild perl with a new static extension).
563
564 Why do setuid perl scripts complain about kernel problems?
565 Some operating systems have bugs in the kernel that make setuid scripts
566 inherently insecure. Perl gives you a number of options (described in
567 perlsec) to work around such systems.
568
569 How can I open a pipe both to and from a command?
570 The IPC::Open2 module (part of the standard perl distribution) is an
571 easy-to-use approach that internally uses pipe(), fork(), and exec() to
572 do the job. Make sure you read the deadlock warnings in its
573 documentation, though (see IPC::Open2). See "Bidirectional
574 Communication with Another Process" in perlipc and "Bidirectional
575 Communication with Yourself" in perlipc
576
577 You may also use the IPC::Open3 module (part of the standard perl
578 distribution), but be warned that it has a different order of arguments
579 from IPC::Open2 (see IPC::Open3).
580
581 Why can't I get the output of a command with system()?
582 You're confusing the purpose of system() and backticks (``). system()
583 runs a command and returns exit status information (as a 16 bit value:
584 the low 7 bits are the signal the process died from, if any, and the
585 high 8 bits are the actual exit value). Backticks (``) run a command
586 and return what it sent to STDOUT.
587
588 my $exit_status = system("mail-users");
589 my $output_string = `ls`;
590
591 How can I capture STDERR from an external command?
592 There are three basic ways of running external commands:
593
594 system $cmd; # using system()
595 my $output = `$cmd`; # using backticks (``)
596 open (my $pipe_fh, "$cmd |"); # using open()
597
598 With system(), both STDOUT and STDERR will go the same place as the
599 script's STDOUT and STDERR, unless the system() command redirects them.
600 Backticks and open() read only the STDOUT of your command.
601
602 You can also use the open3() function from IPC::Open3. Benjamin
603 Goldberg provides some sample code:
604
605 To capture a program's STDOUT, but discard its STDERR:
606
607 use IPC::Open3;
608 use File::Spec;
609 my $in = '';
610 open(NULL, ">", File::Spec->devnull);
611 my $pid = open3($in, \*PH, ">&NULL", "cmd");
612 while( <PH> ) { }
613 waitpid($pid, 0);
614
615 To capture a program's STDERR, but discard its STDOUT:
616
617 use IPC::Open3;
618 use File::Spec;
619 my $in = '';
620 open(NULL, ">", File::Spec->devnull);
621 my $pid = open3($in, ">&NULL", \*PH, "cmd");
622 while( <PH> ) { }
623 waitpid($pid, 0);
624
625 To capture a program's STDERR, and let its STDOUT go to our own STDERR:
626
627 use IPC::Open3;
628 my $in = '';
629 my $pid = open3($in, ">&STDERR", \*PH, "cmd");
630 while( <PH> ) { }
631 waitpid($pid, 0);
632
633 To read both a command's STDOUT and its STDERR separately, you can
634 redirect them to temp files, let the command run, then read the temp
635 files:
636
637 use IPC::Open3;
638 use IO::File;
639 my $in = '';
640 local *CATCHOUT = IO::File->new_tmpfile;
641 local *CATCHERR = IO::File->new_tmpfile;
642 my $pid = open3($in, ">&CATCHOUT", ">&CATCHERR", "cmd");
643 waitpid($pid, 0);
644 seek $_, 0, 0 for \*CATCHOUT, \*CATCHERR;
645 while( <CATCHOUT> ) {}
646 while( <CATCHERR> ) {}
647
648 But there's no real need for both to be tempfiles... the following
649 should work just as well, without deadlocking:
650
651 use IPC::Open3;
652 my $in = '';
653 use IO::File;
654 local *CATCHERR = IO::File->new_tmpfile;
655 my $pid = open3($in, \*CATCHOUT, ">&CATCHERR", "cmd");
656 while( <CATCHOUT> ) {}
657 waitpid($pid, 0);
658 seek CATCHERR, 0, 0;
659 while( <CATCHERR> ) {}
660
661 And it'll be faster, too, since we can begin processing the program's
662 stdout immediately, rather than waiting for the program to finish.
663
664 With any of these, you can change file descriptors before the call:
665
666 open(STDOUT, ">logfile");
667 system("ls");
668
669 or you can use Bourne shell file-descriptor redirection:
670
671 $output = `$cmd 2>some_file`;
672 open (PIPE, "cmd 2>some_file |");
673
674 You can also use file-descriptor redirection to make STDERR a duplicate
675 of STDOUT:
676
677 $output = `$cmd 2>&1`;
678 open (PIPE, "cmd 2>&1 |");
679
680 Note that you cannot simply open STDERR to be a dup of STDOUT in your
681 Perl program and avoid calling the shell to do the redirection. This
682 doesn't work:
683
684 open(STDERR, ">&STDOUT");
685 $alloutput = `cmd args`; # stderr still escapes
686
687 This fails because the open() makes STDERR go to where STDOUT was going
688 at the time of the open(). The backticks then make STDOUT go to a
689 string, but don't change STDERR (which still goes to the old STDOUT).
690
691 Note that you must use Bourne shell (sh(1)) redirection syntax in
692 backticks, not csh(1)! Details on why Perl's system() and backtick and
693 pipe opens all use the Bourne shell are in the versus/csh.whynot
694 article in the "Far More Than You Ever Wanted To Know" collection in
695 <http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> . To capture a
696 command's STDERR and STDOUT together:
697
698 $output = `cmd 2>&1`; # either with backticks
699 $pid = open(PH, "cmd 2>&1 |"); # or with an open pipe
700 while (<PH>) { } # plus a read
701
702 To capture a command's STDOUT but discard its STDERR:
703
704 $output = `cmd 2>/dev/null`; # either with backticks
705 $pid = open(PH, "cmd 2>/dev/null |"); # or with an open pipe
706 while (<PH>) { } # plus a read
707
708 To capture a command's STDERR but discard its STDOUT:
709
710 $output = `cmd 2>&1 1>/dev/null`; # either with backticks
711 $pid = open(PH, "cmd 2>&1 1>/dev/null |"); # or with an open pipe
712 while (<PH>) { } # plus a read
713
714 To exchange a command's STDOUT and STDERR in order to capture the
715 STDERR but leave its STDOUT to come out our old STDERR:
716
717 $output = `cmd 3>&1 1>&2 2>&3 3>&-`; # either with backticks
718 $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
719 while (<PH>) { } # plus a read
720
721 To read both a command's STDOUT and its STDERR separately, it's easiest
722 to redirect them separately to files, and then read from those files
723 when the program is done:
724
725 system("program args 1>program.stdout 2>program.stderr");
726
727 Ordering is important in all these examples. That's because the shell
728 processes file descriptor redirections in strictly left to right order.
729
730 system("prog args 1>tmpfile 2>&1");
731 system("prog args 2>&1 1>tmpfile");
732
733 The first command sends both standard out and standard error to the
734 temporary file. The second command sends only the old standard output
735 there, and the old standard error shows up on the old standard out.
736
737 Why doesn't open() return an error when a pipe open fails?
738 If the second argument to a piped open() contains shell metacharacters,
739 perl fork()s, then exec()s a shell to decode the metacharacters and
740 eventually run the desired program. If the program couldn't be run,
741 it's the shell that gets the message, not Perl. All your Perl program
742 can find out is whether the shell itself could be successfully started.
743 You can still capture the shell's STDERR and check it for error
744 messages. See "How can I capture STDERR from an external command?"
745 elsewhere in this document, or use the IPC::Open3 module.
746
747 If there are no shell metacharacters in the argument of open(), Perl
748 runs the command directly, without using the shell, and can correctly
749 report whether the command started.
750
751 What's wrong with using backticks in a void context?
752 Strictly speaking, nothing. Stylistically speaking, it's not a good way
753 to write maintainable code. Perl has several operators for running
754 external commands. Backticks are one; they collect the output from the
755 command for use in your program. The "system" function is another; it
756 doesn't do this.
757
758 Writing backticks in your program sends a clear message to the readers
759 of your code that you wanted to collect the output of the command. Why
760 send a clear message that isn't true?
761
762 Consider this line:
763
764 `cat /etc/termcap`;
765
766 You forgot to check $? to see whether the program even ran correctly.
767 Even if you wrote
768
769 print `cat /etc/termcap`;
770
771 this code could and probably should be written as
772
773 system("cat /etc/termcap") == 0
774 or die "cat program failed!";
775
776 which will echo the cat command's output as it is generated, instead of
777 waiting until the program has completed to print it out. It also checks
778 the return value.
779
780 "system" also provides direct control over whether shell wildcard
781 processing may take place, whereas backticks do not.
782
783 How can I call backticks without shell processing?
784 This is a bit tricky. You can't simply write the command like this:
785
786 @ok = `grep @opts '$search_string' @filenames`;
787
788 As of Perl 5.8.0, you can use open() with multiple arguments. Just
789 like the list forms of system() and exec(), no shell escapes 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 list.
809 Further examples of this can be found in "Safe Pipe Opens" in perlipc.
810
811 Note that if you're using Windows, no solution to this vexing issue is
812 even possible. Even though Perl emulates fork(), you'll still be stuck,
813 because Windows does not have an argc/argv-style API.
814
815 Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on
816 MS-DOS)?
817 This happens only if your perl is compiled to use stdio instead of
818 perlio, which is the default. Some (maybe all?) stdios set error and
819 eof flags that you may need to clear. The POSIX module defines
820 clearerr() that you can use. That is the technically correct way to do
821 it. Here are some less reliable workarounds:
822
823 1. Try keeping around the seekpointer and go there, like this:
824
825 my $where = tell($log_fh);
826 seek($log_fh, $where, 0);
827
828 2. If that doesn't work, try seeking to a different part of the file
829 and then back.
830
831 3. If that doesn't work, try seeking to a different part of the file,
832 reading something, and then seeking back.
833
834 4. If that doesn't work, give up on your stdio package and use
835 sysread.
836
837 How can I convert my shell script to perl?
838 Learn Perl and rewrite it. Seriously, there's no simple converter.
839 Things that are awkward to do in the shell are easy to do in Perl, and
840 this very awkwardness is what would make a shell->perl converter nigh-
841 on impossible to write. By rewriting it, you'll think about what you're
842 really trying to do, and hopefully will escape the shell's pipeline
843 datastream paradigm, which while convenient for some matters, causes
844 many inefficiencies.
845
846 Can I use perl to run a telnet or ftp session?
847 Try the Net::FTP, TCP::Client, and Net::Telnet modules (available from
848 CPAN). <http://www.cpan.org/scripts/netstuff/telnet.emul.shar> will
849 also help for emulating the telnet protocol, but Net::Telnet is quite
850 probably easier to use.
851
852 If all you want to do is pretend to be telnet but don't need the
853 initial telnet handshaking, then the standard dual-process approach
854 will suffice:
855
856 use IO::Socket; # new in 5.004
857 my $handle = IO::Socket::INET->new('www.perl.com:80')
858 or die "can't connect to port 80 on www.perl.com $!";
859 $handle->autoflush(1);
860 if (fork()) { # XXX: undef means failure
861 select($handle);
862 print while <STDIN>; # everything from stdin to socket
863 } else {
864 print while <$handle>; # everything from socket to stdout
865 }
866 close $handle;
867 exit;
868
869 How can I write expect in Perl?
870 Once upon a time, there was a library called chat2.pl (part of the
871 standard perl distribution), which never really got finished. If you
872 find it somewhere, don't use it. These days, your best bet is to look
873 at the Expect module available from CPAN, which also requires two other
874 modules from CPAN, IO::Pty and IO::Stty.
875
876 Is there a way to hide perl's command line from programs such as "ps"?
877 First of all note that if you're doing this for security reasons (to
878 avoid people seeing passwords, for example) then you should rewrite
879 your program so that critical information is never given as an
880 argument. Hiding the arguments won't make your program completely
881 secure.
882
883 To actually alter the visible command line, you can assign to the
884 variable $0 as documented in perlvar. This won't work on all operating
885 systems, though. Daemon programs like sendmail place their state there,
886 as in:
887
888 $0 = "orcus [accepting connections]";
889
890 I {changed directory, modified my environment} in a perl script. How come
891 the change disappeared when I exited the script? How do I get my
892 changes to be visible?
893 Unix
894 In the strictest sense, it can't be done--the script executes as a
895 different process from the shell it was started from. Changes to a
896 process are not reflected in its parent--only in any children
897 created after the change. There is shell magic that may allow you
898 to fake it by eval()ing the script's output in your shell; check
899 out the comp.unix.questions FAQ for details.
900
901 How do I close a process's filehandle without waiting for it to complete?
902 Assuming your system supports such things, just send an appropriate
903 signal to the process (see "kill" in perlfunc). It's common to first
904 send a TERM signal, wait a little bit, and then send a KILL signal to
905 finish it off.
906
907 How do I fork a daemon process?
908 If by daemon process you mean one that's detached (disassociated from
909 its tty), then the following process is reported to work on most
910 Unixish systems. Non-Unix users should check their Your_OS::Process
911 module for other solutions.
912
913 • Open /dev/tty and use the TIOCNOTTY ioctl on it. See tty(1) for
914 details. Or better yet, you can just use the POSIX::setsid()
915 function, so you don't have to worry about process groups.
916
917 • Change directory to /
918
919 • Reopen STDIN, STDOUT, and STDERR so they're not connected to the
920 old tty.
921
922 • Background yourself like this:
923
924 fork && exit;
925
926 The Proc::Daemon module, available from CPAN, provides a function to
927 perform these actions for you.
928
929 How do I find out if I'm running interactively or not?
930 (contributed by brian d foy)
931
932 This is a difficult question to answer, and the best answer is only a
933 guess.
934
935 What do you really want to know? If you merely want to know if one of
936 your filehandles is connected to a terminal, you can try the "-t" file
937 test:
938
939 if( -t STDOUT ) {
940 print "I'm connected to a terminal!\n";
941 }
942
943 However, you might be out of luck if you expect that means there is a
944 real person on the other side. With the Expect module, another program
945 can pretend to be a person. The program might even come close to
946 passing the Turing test.
947
948 The IO::Interactive module does the best it can to give you an answer.
949 Its "is_interactive" function returns an output filehandle; that
950 filehandle points to standard output if the module thinks the session
951 is interactive. Otherwise, the filehandle is a null handle that simply
952 discards the output:
953
954 use IO::Interactive;
955
956 print { is_interactive } "I might go to standard output!\n";
957
958 This still doesn't guarantee that a real person is answering your
959 prompts or reading your output.
960
961 If you want to know how to handle automated testing for your
962 distribution, you can check the environment. The CPAN Testers, for
963 instance, set the value of "AUTOMATED_TESTING":
964
965 unless( $ENV{AUTOMATED_TESTING} ) {
966 print "Hello interactive tester!\n";
967 }
968
969 How do I timeout a slow event?
970 Use the alarm() function, probably in conjunction with a signal
971 handler, as documented in "Signals" in perlipc and the section on
972 "Signals" in the Camel. You may instead use the more flexible
973 Sys::AlarmCall module available from CPAN.
974
975 The alarm() function is not implemented on all versions of Windows.
976 Check the documentation for your specific version of Perl.
977
978 How do I set CPU limits?
979 (contributed by Xho)
980
981 Use the BSD::Resource module from CPAN. As an example:
982
983 use BSD::Resource;
984 setrlimit(RLIMIT_CPU,10,20) or die $!;
985
986 This sets the soft and hard limits to 10 and 20 seconds, respectively.
987 After 10 seconds of time spent running on the CPU (not "wall" time),
988 the process will be sent a signal (XCPU on some systems) which, if not
989 trapped, will cause the process to terminate. If that signal is
990 trapped, then after 10 more seconds (20 seconds in total) the process
991 will be killed with a non-trappable signal.
992
993 See the BSD::Resource and your systems documentation for the gory
994 details.
995
996 How do I avoid zombies on a Unix system?
997 Use the reaper code from "Signals" in perlipc to call wait() when a
998 SIGCHLD is received, or else use the double-fork technique described in
999 "How do I start a process in the background?" in perlfaq8.
1000
1001 How do I use an SQL database?
1002 The DBI module provides an abstract interface to most database servers
1003 and types, including Oracle, DB2, Sybase, mysql, Postgresql, ODBC, and
1004 flat files. The DBI module accesses each database type through a
1005 database driver, or DBD. You can see a complete list of available
1006 drivers on CPAN: <http://www.cpan.org/modules/by-module/DBD/> . You
1007 can read more about DBI on <http://dbi.perl.org/> .
1008
1009 Other modules provide more specific access: Win32::ODBC, Alzabo,
1010 "iodbc", and others found on CPAN Search: <https://metacpan.org/> .
1011
1012 How do I make a system() exit on control-C?
1013 You can't. You need to imitate the system() call (see perlipc for
1014 sample code) and then have a signal handler for the INT signal that
1015 passes the signal on to the subprocess. Or you can check for it:
1016
1017 $rc = system($cmd);
1018 if ($rc & 127) { die "signal death" }
1019
1020 How do I open a file without blocking?
1021 If you're lucky enough to be using a system that supports non-blocking
1022 reads (most Unixish systems do), you need only to use the "O_NDELAY" or
1023 "O_NONBLOCK" flag from the "Fcntl" module in conjunction with
1024 sysopen():
1025
1026 use Fcntl;
1027 sysopen(my $fh, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)
1028 or die "can't open /foo/somefile: $!":
1029
1030 How do I tell the difference between errors from the shell and perl?
1031 (answer contributed by brian d foy)
1032
1033 When you run a Perl script, something else is running the script for
1034 you, and that something else may output error messages. The script
1035 might emit its own warnings and error messages. Most of the time you
1036 cannot tell who said what.
1037
1038 You probably cannot fix the thing that runs perl, but you can change
1039 how perl outputs its warnings by defining a custom warning and die
1040 functions.
1041
1042 Consider this script, which has an error you may not notice
1043 immediately.
1044
1045 #!/usr/locl/bin/perl
1046
1047 print "Hello World\n";
1048
1049 I get an error when I run this from my shell (which happens to be
1050 bash). That may look like perl forgot it has a print() function, but my
1051 shebang line is not the path to perl, so the shell runs the script, and
1052 I get the error.
1053
1054 $ ./test
1055 ./test: line 3: print: command not found
1056
1057 A quick and dirty fix involves a little bit of code, but this may be
1058 all you need to figure out the problem.
1059
1060 #!/usr/bin/perl -w
1061
1062 BEGIN {
1063 $SIG{__WARN__} = sub{ print STDERR "Perl: ", @_; };
1064 $SIG{__DIE__} = sub{ print STDERR "Perl: ", @_; exit 1};
1065 }
1066
1067 $a = 1 + undef;
1068 $x / 0;
1069 __END__
1070
1071 The perl message comes out with "Perl" in front. The "BEGIN" block
1072 works at compile time so all of the compilation errors and warnings get
1073 the "Perl:" prefix too.
1074
1075 Perl: Useless use of division (/) in void context at ./test line 9.
1076 Perl: Name "main::a" used only once: possible typo at ./test line 8.
1077 Perl: Name "main::x" used only once: possible typo at ./test line 9.
1078 Perl: Use of uninitialized value in addition (+) at ./test line 8.
1079 Perl: Use of uninitialized value in division (/) at ./test line 9.
1080 Perl: Illegal division by zero at ./test line 9.
1081 Perl: Illegal division by zero at -e line 3.
1082
1083 If I don't see that "Perl:", it's not from perl.
1084
1085 You could also just know all the perl errors, and although there are
1086 some people who may know all of them, you probably don't. However, they
1087 all should be in the perldiag manpage. If you don't find the error in
1088 there, it probably isn't a perl error.
1089
1090 Looking up every message is not the easiest way, so let perl to do it
1091 for you. Use the diagnostics pragma with turns perl's normal messages
1092 into longer discussions on the topic.
1093
1094 use diagnostics;
1095
1096 If you don't get a paragraph or two of expanded discussion, it might
1097 not be perl's message.
1098
1099 How do I install a module from CPAN?
1100 (contributed by brian d foy)
1101
1102 The easiest way is to have a module also named CPAN do it for you by
1103 using the "cpan" command that comes with Perl. You can give it a list
1104 of modules to install:
1105
1106 $ cpan IO::Interactive Getopt::Whatever
1107
1108 If you prefer "CPANPLUS", it's just as easy:
1109
1110 $ cpanp i IO::Interactive Getopt::Whatever
1111
1112 If you want to install a distribution from the current directory, you
1113 can tell "CPAN.pm" to install "." (the full stop):
1114
1115 $ cpan .
1116
1117 See the documentation for either of those commands to see what else you
1118 can do.
1119
1120 If you want to try to install a distribution by yourself, resolving all
1121 dependencies on your own, you follow one of two possible build paths.
1122
1123 For distributions that use Makefile.PL:
1124
1125 $ perl Makefile.PL
1126 $ make test install
1127
1128 For distributions that use Build.PL:
1129
1130 $ perl Build.PL
1131 $ ./Build test
1132 $ ./Build install
1133
1134 Some distributions may need to link to libraries or other third-party
1135 code and their build and installation sequences may be more
1136 complicated. Check any README or INSTALL files that you may find.
1137
1138 What's the difference between require and use?
1139 (contributed by brian d foy)
1140
1141 Perl runs "require" statement at run-time. Once Perl loads, compiles,
1142 and runs the file, it doesn't do anything else. The "use" statement is
1143 the same as a "require" run at compile-time, but Perl also calls the
1144 "import" method for the loaded package. These two are the same:
1145
1146 use MODULE qw(import list);
1147
1148 BEGIN {
1149 require MODULE;
1150 MODULE->import(import list);
1151 }
1152
1153 However, you can suppress the "import" by using an explicit, empty
1154 import list. Both of these still happen at compile-time:
1155
1156 use MODULE ();
1157
1158 BEGIN {
1159 require MODULE;
1160 }
1161
1162 Since "use" will also call the "import" method, the actual value for
1163 "MODULE" must be a bareword. That is, "use" cannot load files by name,
1164 although "require" can:
1165
1166 require "$ENV{HOME}/lib/Foo.pm"; # no @INC searching!
1167
1168 See the entry for "use" in perlfunc for more details.
1169
1170 How do I keep my own module/library directory?
1171 When you build modules, tell Perl where to install the modules.
1172
1173 If you want to install modules for your own use, the easiest way might
1174 be local::lib, which you can download from CPAN. It sets various
1175 installation settings for you, and uses those same settings within your
1176 programs.
1177
1178 If you want more flexibility, you need to configure your CPAN client
1179 for your particular situation.
1180
1181 For "Makefile.PL"-based distributions, use the INSTALL_BASE option when
1182 generating Makefiles:
1183
1184 perl Makefile.PL INSTALL_BASE=/mydir/perl
1185
1186 You can set this in your "CPAN.pm" configuration so modules
1187 automatically install in your private library directory when you use
1188 the CPAN.pm shell:
1189
1190 % cpan
1191 cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
1192 cpan> o conf commit
1193
1194 For "Build.PL"-based distributions, use the --install_base option:
1195
1196 perl Build.PL --install_base /mydir/perl
1197
1198 You can configure "CPAN.pm" to automatically use this option too:
1199
1200 % cpan
1201 cpan> o conf mbuild_arg "--install_base /mydir/perl"
1202 cpan> o conf commit
1203
1204 INSTALL_BASE tells these tools to put your modules into
1205 /mydir/perl/lib/perl5. See "How do I add a directory to my include path
1206 (@INC) at runtime?" for details on how to run your newly installed
1207 modules.
1208
1209 There is one caveat with INSTALL_BASE, though, since it acts
1210 differently from the PREFIX and LIB settings that older versions of
1211 ExtUtils::MakeMaker advocated. INSTALL_BASE does not support installing
1212 modules for multiple versions of Perl or different architectures under
1213 the same directory. You should consider whether you really want that
1214 and, if you do, use the older PREFIX and LIB settings. See the
1215 ExtUtils::Makemaker documentation for more details.
1216
1217 How do I add the directory my program lives in to the module/library search
1218 path?
1219 (contributed by brian d foy)
1220
1221 If you know the directory already, you can add it to @INC as you would
1222 for any other directory. You might "use lib" if you know the directory
1223 at compile time:
1224
1225 use lib $directory;
1226
1227 The trick in this task is to find the directory. Before your script
1228 does anything else (such as a "chdir"), you can get the current working
1229 directory with the "Cwd" module, which comes with Perl:
1230
1231 BEGIN {
1232 use Cwd;
1233 our $directory = cwd;
1234 }
1235
1236 use lib $directory;
1237
1238 You can do a similar thing with the value of $0, which holds the script
1239 name. That might hold a relative path, but "rel2abs" can turn it into
1240 an absolute path. Once you have the
1241
1242 BEGIN {
1243 use File::Spec::Functions qw(rel2abs);
1244 use File::Basename qw(dirname);
1245
1246 my $path = rel2abs( $0 );
1247 our $directory = dirname( $path );
1248 }
1249
1250 use lib $directory;
1251
1252 The FindBin module, which comes with Perl, might work. It finds the
1253 directory of the currently running script and puts it in $Bin, which
1254 you can then use to construct the right library path:
1255
1256 use FindBin qw($Bin);
1257
1258 You can also use local::lib to do much of the same thing. Install
1259 modules using local::lib's settings then use the module in your
1260 program:
1261
1262 use local::lib; # sets up a local lib at ~/perl5
1263
1264 See the local::lib documentation for more details.
1265
1266 How do I add a directory to my include path (@INC) at runtime?
1267 Here are the suggested ways of modifying your include path, including
1268 environment variables, run-time switches, and in-code statements:
1269
1270 the "PERLLIB" environment variable
1271 $ export PERLLIB=/path/to/my/dir
1272 $ perl program.pl
1273
1274 the "PERL5LIB" environment variable
1275 $ export PERL5LIB=/path/to/my/dir
1276 $ perl program.pl
1277
1278 the "perl -Idir" command line flag
1279 $ perl -I/path/to/my/dir program.pl
1280
1281 the "lib" pragma:
1282 use lib "$ENV{HOME}/myown_perllib";
1283
1284 the local::lib module:
1285 use local::lib;
1286
1287 use local::lib "~/myown_perllib";
1288
1289 Where are modules installed?
1290 Modules are installed on a case-by-case basis (as provided by the
1291 methods described in the previous section), and in the operating
1292 system. All of these paths are stored in @INC, which you can display
1293 with the one-liner
1294
1295 perl -e 'print join("\n",@INC,"")'
1296
1297 The same information is displayed at the end of the output from the
1298 command
1299
1300 perl -V
1301
1302 To find out where a module's source code is located, use
1303
1304 perldoc -l Encode
1305
1306 to display the path to the module. In some cases (for example, the
1307 "AutoLoader" module), this command will show the path to a separate
1308 "pod" file; the module itself should be in the same directory, with a
1309 'pm' file extension.
1310
1311 What is socket.ph and where do I get it?
1312 It's a Perl 4 style file defining values for system networking
1313 constants. Sometimes it is built using h2ph when Perl is installed, but
1314 other times it is not. Modern programs should use "use Socket;"
1315 instead.
1316
1318 Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other
1319 authors as noted. All rights reserved.
1320
1321 This documentation is free; you can redistribute it and/or modify it
1322 under the same terms as Perl itself.
1323
1324 Irrespective of its distribution, all code examples in this file are
1325 hereby placed into the public domain. You are permitted and encouraged
1326 to use this code in your own programs for fun or for profit as you see
1327 fit. A simple comment in the code giving credit would be courteous but
1328 is not required.
1329
1330
1331
1332perl v5.36.1 2023-08-24 perlfaq8(3)