Debian Codegraph @

upstream/debian-unstable/man1/perlfaq8.1

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