Debian Codegraph @

upstream/mageia-cauldron/man1/perlfaq8.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man v6.0.2 (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 .\" Required to disable full justification in groff 1.23.0.
57 .if n .ds AD l
58 .\" ========================================================================
59 .\"
60 .IX Title "PERLFAQ8 1"
61 .TH PERLFAQ8 1 2025-06-24 "perl v5.42.0" "Perl Programmers Reference Guide"
62 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
63 .\" way too many mistakes in technical documents.
64 .if n .ad l
65 .nh
66 .SH NAME
67 perlfaq8 \- System Interaction
68 .SH VERSION
69 .IX Header "VERSION"
70 version 5.20250619
71 .SH DESCRIPTION
72 .IX Header "DESCRIPTION"
73 This section of the Perl FAQ covers questions involving operating
74 system interaction. Topics include interprocess communication (IPC),
75 control over the user\-interface (keyboard, screen and pointing
76 devices), and most anything else not related to data manipulation.
77 .PP
78 Read the FAQs and documentation specific to the port of perl to your
79 operating system (eg, perlvms, perlplan9, ...). These should
80 contain more detailed information on the vagaries of your perl.
81 .SS "How do I find out which operating system I\*(Aqm running under?"
82 .IX Subsection "How do I find out which operating system I'm running under?"
83 The \f(CW$^O\fR variable (\f(CW$OSNAME\fR if you use \f(CW\*(C`English\*(C'\fR) contains an
84 indication of the name of the operating system (not its release
85 number) that your perl binary was built for.
86 .SS "Why does \fBexec()\fP not return?"
87 .IX Xref "exec system fork open pipe"
88 .IX Subsection "Why does exec() not return?"
89 (contributed by brian d foy)
90 .PP
91 The \f(CW\*(C`exec\*(C'\fR function\*(Aqs job is to turn your process into another
92 command and never to return. If that\*(Aqs not what you want to do, don\*(Aqt
93 use \f(CW\*(C`exec\*(C'\fR. :)
94 .PP
95 If you want to run an external command and still keep your Perl process
96 going, look at a piped \f(CW\*(C`open\*(C'\fR, \f(CW\*(C`fork\*(C'\fR, or \f(CW\*(C`system\*(C'\fR.
97 .SS "How do I do fancy stuff with the keyboard/screen/mouse?"
98 .IX Subsection "How do I do fancy stuff with the keyboard/screen/mouse?"
99 How you access/control keyboards, screens, and pointing devices
100 ("mice") is system\-dependent. Try the following modules:
101 .IP Keyboard 4
102 .IX Item "Keyboard"
103 .Vb 5
104 \& Term::Cap Standard perl distribution
105 \& Term::ReadKey CPAN
106 \& Term::ReadLine::Gnu CPAN
107 \& Term::ReadLine::Perl CPAN
108 \& Term::Screen CPAN
109 .Ve
110 .IP Screen 4
111 .IX Item "Screen"
112 .Vb 3
113 \& Term::Cap Standard perl distribution
114 \& Curses CPAN
115 \& Term::ANSIColor CPAN
116 .Ve
117 .IP Mouse 4
118 .IX Item "Mouse"
119 .Vb 4
120 \& Tk CPAN
121 \& Wx CPAN
122 \& Gtk2 CPAN
123 \& Qt4 kdebindings4 package
124 .Ve
125 .PP
126 Some of these specific cases are shown as examples in other answers
127 in this section of the perlfaq.
128 .SS "How do I print something out in color?"
129 .IX Subsection "How do I print something out in color?"
130 In general, you don\*(Aqt, because you don\*(Aqt know whether
131 the recipient has a color\-aware display device. If you
132 know that they have an ANSI terminal that understands
133 color, you can use the Term::ANSIColor module from CPAN:
134 .PP
135 .Vb 3
136 \& use Term::ANSIColor;
137 \& print color("red"), "Stop!\en", color("reset");
138 \& print color("green"), "Go!\en", color("reset");
139 .Ve
140 .PP
141 Or like this:
142 .PP
143 .Vb 3
144 \& use Term::ANSIColor qw(:constants);
145 \& print RED, "Stop!\en", RESET;
146 \& print GREEN, "Go!\en", RESET;
147 .Ve
148 .SS "How do I read just one key without waiting for a return key?"
149 .IX Subsection "How do I read just one key without waiting for a return key?"
150 Controlling input buffering is a remarkably system\-dependent matter.
151 On many systems, you can just use the \fBstty\fR command as shown in
152 "getc" in perlfunc, but as you see, that\*(Aqs already getting you into
153 portability snags.
154 .PP
155 .Vb 6
156 \& open(TTY, "+</dev/tty") or die "no tty: $!";
157 \& system "stty cbreak </dev/tty >/dev/tty 2>&1";
158 \& $key = getc(TTY); # perhaps this works
159 \& # OR ELSE
160 \& sysread(TTY, $key, 1); # probably this does
161 \& system "stty \-cbreak </dev/tty >/dev/tty 2>&1";
162 .Ve
163 .PP
164 The Term::ReadKey module from CPAN offers an easy\-to\-use interface that
165 should be more efficient than shelling out to \fBstty\fR for each key.
166 It even includes limited support for Windows.
167 .PP
168 .Vb 4
169 \& use Term::ReadKey;
170 \& ReadMode(\*(Aqcbreak\*(Aq);
171 \& $key = ReadKey(0);
172 \& ReadMode(\*(Aqnormal\*(Aq);
173 .Ve
174 .PP
175 However, using the code requires that you have a working C compiler
176 and can use it to build and install a CPAN module. Here\*(Aqs a solution
177 using the standard POSIX module, which is already on your system
178 (assuming your system supports POSIX).
179 .PP
180 .Vb 2
181 \& use HotKey;
182 \& $key = readkey();
183 .Ve
184 .PP
185 And here\*(Aqs the \f(CW\*(C`HotKey\*(C'\fR module, which hides the somewhat mystifying calls
186 to manipulate the POSIX termios structures.
187 .PP
188 .Vb 2
189 \& # HotKey.pm
190 \& package HotKey;
191 \&
192 \& use strict;
193 \& use warnings;
194 \&
195 \& use parent \*(AqExporter\*(Aq;
196 \& our @EXPORT = qw(cbreak cooked readkey);
197 \&
198 \& use POSIX qw(:termios_h);
199 \& my ($term, $oterm, $echo, $noecho, $fd_stdin);
200 \&
201 \& $fd_stdin = fileno(STDIN);
202 \& $term = POSIX::Termios\->new();
203 \& $term\->getattr($fd_stdin);
204 \& $oterm = $term\->getlflag();
205 \&
206 \& $echo = ECHO | ECHOK | ICANON;
207 \& $noecho = $oterm & ~$echo;
208 \&
209 \& sub cbreak {
210 \& $term\->setlflag($noecho); # ok, so i don\*(Aqt want echo either
211 \& $term\->setcc(VTIME, 1);
212 \& $term\->setattr($fd_stdin, TCSANOW);
213 \& }
214 \&
215 \& sub cooked {
216 \& $term\->setlflag($oterm);
217 \& $term\->setcc(VTIME, 0);
218 \& $term\->setattr($fd_stdin, TCSANOW);
219 \& }
220 \&
221 \& sub readkey {
222 \& my $key = \*(Aq\*(Aq;
223 \& cbreak();
224 \& sysread(STDIN, $key, 1);
225 \& cooked();
226 \& return $key;
227 \& }
228 \&
229 \& END { cooked() }
230 \&
231 \& 1;
232 .Ve
233 .SS "How do I check whether input is ready on the keyboard?"
234 .IX Subsection "How do I check whether input is ready on the keyboard?"
235 The easiest way to do this is to read a key in nonblocking mode with the
236 Term::ReadKey module from CPAN, passing it an argument of \-1 to indicate
237 not to block:
238 .PP
239 .Vb 1
240 \& use Term::ReadKey;
241 \&
242 \& ReadMode(\*(Aqcbreak\*(Aq);
243 \&
244 \& if (defined (my $char = ReadKey(\-1)) ) {
245 \& # input was waiting and it was $char
246 \& } else {
247 \& # no input was waiting
248 \& }
249 \&
250 \& ReadMode(\*(Aqnormal\*(Aq); # restore normal tty settings
251 .Ve
252 .SS "How do I clear the screen?"
253 .IX Subsection "How do I clear the screen?"
254 (contributed by brian d foy)
255 .PP
256 To clear the screen, you just have to print the special sequence
257 that tells the terminal to clear the screen. Once you have that
258 sequence, output it when you want to clear the screen.
259 .PP
260 You can use the Term::ANSIScreen module to get the special
261 sequence. Import the \f(CW\*(C`cls\*(C'\fR function (or the \f(CW\*(C`:screen\*(C'\fR tag):
262 .PP
263 .Vb 2
264 \& use Term::ANSIScreen qw(cls);
265 \& my $clear_screen = cls();
266 \&
267 \& print $clear_screen;
268 .Ve
269 .PP
270 The Term::Cap module can also get the special sequence if you want
271 to deal with the low\-level details of terminal control. The \f(CW\*(C`Tputs\*(C'\fR
272 method returns the string for the given capability:
273 .PP
274 .Vb 1
275 \& use Term::Cap;
276 \&
277 \& my $terminal = Term::Cap\->Tgetent( { OSPEED => 9600 } );
278 \& my $clear_screen = $terminal\->Tputs(\*(Aqcl\*(Aq);
279 \&
280 \& print $clear_screen;
281 .Ve
282 .PP
283 On Windows, you can use the Win32::Console module. After creating
284 an object for the output filehandle you want to affect, call the
285 \&\f(CW\*(C`Cls\*(C'\fR method:
286 .PP
287 .Vb 1
288 \& Win32::Console;
289 \&
290 \& my $OUT = Win32::Console\->new(STD_OUTPUT_HANDLE);
291 \& $OUT\->Cls;
292 .Ve
293 .PP
294 If you have a command\-line program that does the job, you can call
295 it in backticks to capture whatever it outputs so you can use it
296 later:
297 .PP
298 .Vb 1
299 \& my $clear_string = \`clear\`;
300 \&
301 \& print $clear_string;
302 .Ve
303 .SS "How do I get the screen size?"
304 .IX Subsection "How do I get the screen size?"
305 If you have Term::ReadKey module installed from CPAN,
306 you can use it to fetch the width and height in characters
307 and in pixels:
308 .PP
309 .Vb 2
310 \& use Term::ReadKey;
311 \& my ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
312 .Ve
313 .PP
314 This is more portable than the raw \f(CW\*(C`ioctl\*(C'\fR, but not as
315 illustrative:
316 .PP
317 .Vb 10
318 \& require \*(Aq./sys/ioctl.ph\*(Aq;
319 \& die "no TIOCGWINSZ " unless defined &TIOCGWINSZ;
320 \& open(my $tty_fh, "+</dev/tty") or die "No tty: $!";
321 \& unless (ioctl($tty_fh, &TIOCGWINSZ, $winsize=\*(Aq\*(Aq)) {
322 \& die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\en", &TIOCGWINSZ;
323 \& }
324 \& my ($row, $col, $xpixel, $ypixel) = unpack(\*(AqS4\*(Aq, $winsize);
325 \& print "(row,col) = ($row,$col)";
326 \& print " (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
327 \& print "\en";
328 .Ve
329 .SS "How do I ask the user for a password?"
330 .IX Subsection "How do I ask the user for a password?"
331 (This question has nothing to do with the web. See a different
332 FAQ for that.)
333 .PP
334 There\*(Aqs an example of this in "crypt" in perlfunc. First, you put the
335 terminal into "no echo" mode, then just read the password normally.
336 You may do this with an old\-style \f(CWioctl()\fR function, POSIX terminal
337 control (see POSIX or its documentation the Camel Book), or a call
338 to the \fBstty\fR program, with varying degrees of portability.
339 .PP
340 You can also do this for most systems using the Term::ReadKey module
341 from CPAN, which is easier to use and in theory more portable.
342 .PP
343 .Vb 1
344 \& use Term::ReadKey;
345 \&
346 \& ReadMode(\*(Aqnoecho\*(Aq);
347 \& my $password = ReadLine(0);
348 .Ve
349 .SS "How do I read and write the serial port?"
350 .IX Subsection "How do I read and write the serial port?"
351 This depends on which operating system your program is running on. In
352 the case of Unix, the serial ports will be accessible through files in
353 \&\f(CW\*(C`/dev\*(C'\fR; on other systems, device names will doubtless differ.
354 Several problem areas common to all device interaction are the
355 following:
356 .IP lockfiles 4
357 .IX Item "lockfiles"
358 Your system may use lockfiles to control multiple access. Make sure
359 you follow the correct protocol. Unpredictable behavior can result
360 from multiple processes reading from one device.
361 .IP "open mode" 4
362 .IX Item "open mode"
363 If you expect to use both read and write operations on the device,
364 you\*(Aqll have to open it for update (see "open" in perlfunc for
365 details). You may wish to open it without running the risk of
366 blocking by using \f(CWsysopen()\fR and \f(CW\*(C`O_RDWR|O_NDELAY|O_NOCTTY\*(C'\fR from the
367 Fcntl module (part of the standard perl distribution). See
368 "sysopen" in perlfunc for more on this approach.
369 .IP "end of line" 4
370 .IX Item "end of line"
371 Some devices will be expecting a "\er" at the end of each line rather
372 than a "\en". In some ports of perl, "\er" and "\en" are different from
373 their usual (Unix) ASCII values of "\e015" and "\e012". You may have to
374 give the numeric values you want directly, using octal ("\e015"), hex
375 ("0x0D"), or as a control\-character specification ("\ecM").
376 .Sp
377 .Vb 2
378 \& print DEV "atv1\e012"; # wrong, for some devices
379 \& print DEV "atv1\e015"; # right, for some devices
380 .Ve
381 .Sp
382 Even though with normal text files a "\en" will do the trick, there is
383 still no unified scheme for terminating a line that is portable
384 between Unix, DOS/Win, and Macintosh, except to terminate \fIALL\fR line
385 ends with "\e015\e012", and strip what you don\*(Aqt need from the output.
386 This applies especially to socket I/O and autoflushing, discussed
387 next.
388 .IP "flushing output" 4
389 .IX Item "flushing output"
390 If you expect characters to get to your device when you \f(CWprint()\fR them,
391 you\*(Aqll want to autoflush that filehandle. You can use \f(CWselect()\fR
392 and the \f(CW$|\fR variable to control autoflushing (see "$|" in perlvar
393 and "select" in perlfunc, or perlfaq5, "How do I flush/unbuffer an
394 output filehandle? Why must I do this?"):
395 .Sp
396 .Vb 3
397 \& my $old_handle = select($dev_fh);
398 \& $| = 1;
399 \& select($old_handle);
400 .Ve
401 .Sp
402 You\*(Aqll also see code that does this without a temporary variable, as in
403 .Sp
404 .Vb 1
405 \& select((select($deb_handle), $| = 1)[0]);
406 .Ve
407 .Sp
408 Or if you don\*(Aqt mind pulling in a few thousand lines
409 of code just because you\*(Aqre afraid of a little \f(CW$|\fR variable:
410 .Sp
411 .Vb 2
412 \& use IO::Handle;
413 \& $dev_fh\->autoflush(1);
414 .Ve
415 .Sp
416 As mentioned in the previous item, this still doesn\*(Aqt work when using
417 socket I/O between Unix and Macintosh. You\*(Aqll need to hard code your
418 line terminators, in that case.
419 .IP "non\-blocking input" 4
420 .IX Item "non-blocking input"
421 If you are doing a blocking \f(CWread()\fR or \f(CWsysread()\fR, you\*(Aqll have to
422 arrange for an alarm handler to provide a timeout (see
423 "alarm" in perlfunc). If you have a non\-blocking open, you\*(Aqll likely
424 have a non\-blocking read, which means you may have to use a 4\-arg
425 \&\f(CWselect()\fR to determine whether I/O is ready on that device (see
426 "select" in perlfunc.
427 .PP
428 While trying to read from his caller\-id box, the notorious Jamie
429 Zawinski \f(CW\*(C`<[email protected]>\*(C'\fR, after much gnashing of teeth and
430 fighting with \f(CW\*(C`sysread\*(C'\fR, \f(CW\*(C`sysopen\*(C'\fR, POSIX\*(Aqs \f(CW\*(C`tcgetattr\*(C'\fR business,
431 and various other functions that go bump in the night, finally came up
432 with this:
433 .PP
434 .Vb 10
435 \& sub open_modem {
436 \& use IPC::Open2;
437 \& my $stty = \`/bin/stty \-g\`;
438 \& open2( \e*MODEM_IN, \e*MODEM_OUT, "cu \-l$modem_device \-s2400 2>&1");
439 \& # starting cu hoses /dev/tty\*(Aqs stty settings, even when it has
440 \& # been opened on a pipe...
441 \& system("/bin/stty $stty");
442 \& $_ = <MODEM_IN>;
443 \& chomp;
444 \& if ( !m/^Connected/ ) {
445 \& print STDERR "$0: cu printed \`$_\*(Aq instead of \`Connected\*(Aq\en";
446 \& }
447 \& }
448 .Ve
449 .SS "How do I decode encrypted password files?"
450 .IX Subsection "How do I decode encrypted password files?"
451 You spend lots and lots of money on dedicated hardware, but this is
452 bound to get you talked about.
453 .PP
454 Seriously, you can\*(Aqt if they are Unix password files\-\-the Unix
455 password system employs one\-way encryption. It\*(Aqs more like hashing
456 than encryption. The best you can do is check whether something else
457 hashes to the same string. You can\*(Aqt turn a hash back into the
458 original string. Programs like Crack can forcibly (and intelligently)
459 try to guess passwords, but don\*(Aqt (can\*(Aqt) guarantee quick success.
460 .PP
461 If you\*(Aqre worried about users selecting bad passwords, you should
462 proactively check when they try to change their password (by modifying
463 \&\fBpasswd\fR\|(1), for example).
464 .SS "How do I start a process in the background?"
465 .IX Subsection "How do I start a process in the background?"
466 (contributed by brian d foy)
467 .PP
468 There\*(Aqs not a single way to run code in the background so you don\*(Aqt
469 have to wait for it to finish before your program moves on to other
470 tasks. Process management depends on your particular operating system,
471 and many of the techniques are covered in perlipc.
472 .PP
473 Several CPAN modules may be able to help, including IPC::Open2 or
474 IPC::Open3, IPC::Run, Parallel::Jobs,
475 Parallel::ForkManager, POE, Proc::Background, and
476 Win32::Process. There are many other modules you might use, so
477 check those namespaces for other options too.
478 .PP
479 If you are on a Unix\-like system, you might be able to get away with a
480 system call where you put an \f(CW\*(C`&\*(C'\fR on the end of the command:
481 .PP
482 .Vb 1
483 \& system("cmd &")
484 .Ve
485 .PP
486 You can also try using \f(CW\*(C`fork\*(C'\fR, as described in perlfunc (although
487 this is the same thing that many of the modules will do for you).
488 .IP "STDIN, STDOUT, and STDERR are shared" 4
489 .IX Item "STDIN, STDOUT, and STDERR are shared"
490 Both the main process and the backgrounded one (the "child" process)
491 share the same STDIN, STDOUT and STDERR filehandles. If both try to
492 access them at once, strange things can happen. You may want to close
493 or reopen these for the child. You can get around this with
494 \&\f(CW\*(C`open\*(C'\fRing a pipe (see "open" in perlfunc) but on some systems this
495 means that the child process cannot outlive the parent.
496 .IP Signals 4
497 .IX Item "Signals"
498 You\*(Aqll have to catch the SIGCHLD signal, and possibly SIGPIPE too.
499 SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is
500 sent when you write to a filehandle whose child process has closed (an
501 untrapped SIGPIPE can cause your program to silently die). This is
502 not an issue with \f(CWsystem("cmd&")\fR.
503 .IP Zombies 4
504 .IX Item "Zombies"
505 You have to be prepared to "reap" the child process when it finishes.
506 .Sp
507 .Vb 1
508 \& $SIG{CHLD} = sub { wait };
509 \&
510 \& $SIG{CHLD} = \*(AqIGNORE\*(Aq;
511 .Ve
512 .Sp
513 You can also use a double fork. You immediately \f(CWwait()\fR for your
514 first child, and the init daemon will \f(CWwait()\fR for your grandchild once
515 it exits.
516 .Sp
517 .Vb 8
518 \& unless ($pid = fork) {
519 \& unless (fork) {
520 \& exec "what you really wanna do";
521 \& die "exec failed!";
522 \& }
523 \& exit 0;
524 \& }
525 \& waitpid($pid, 0);
526 .Ve
527 .Sp
528 See "Signals" in perlipc for other examples of code to do this.
529 Zombies are not an issue with \f(CW\*(C`system("prog &")\*(C'\fR.
530 .SS "How do I trap control characters/signals?"
531 .IX Subsection "How do I trap control characters/signals?"
532 You don\*(Aqt actually "trap" a control character. Instead, that character
533 generates a signal which is sent to your terminal\*(Aqs currently
534 foregrounded process group, which you then trap in your process.
535 Signals are documented in "Signals" in perlipc and the
536 section on "Signals" in the Camel.
537 .PP
538 You can set the values of the \f(CW%SIG\fR hash to be the functions you want
539 to handle the signal. After perl catches the signal, it looks in \f(CW%SIG\fR
540 for a key with the same name as the signal, then calls the subroutine
541 value for that key.
542 .PP
543 .Vb 1
544 \& # as an anonymous subroutine
545 \&
546 \& $SIG{INT} = sub { syswrite(STDERR, "ouch\en", 5 ) };
547 \&
548 \& # or a reference to a function
549 \&
550 \& $SIG{INT} = \e&ouch;
551 \&
552 \& # or the name of the function as a string
553 \&
554 \& $SIG{INT} = "ouch";
555 .Ve
556 .PP
557 Perl versions before 5.8 had in its C source code signal handlers which
558 would catch the signal and possibly run a Perl function that you had set
559 in \f(CW%SIG\fR. This violated the rules of signal handling at that level
560 causing perl to dump core. Since version 5.8.0, perl looks at \f(CW%SIG\fR
561 \&\fBafter\fR the signal has been caught, rather than while it is being caught.
562 Previous versions of this answer were incorrect.
563 .SS "How do I modify the shadow password file on a Unix system?"
564 .IX Subsection "How do I modify the shadow password file on a Unix system?"
565 If perl was installed correctly and your shadow library was written
566 properly, the \f(CW\*(C`getpw*()\*(C'\fR functions described in perlfunc should in
567 theory provide (read\-only) access to entries in the shadow password
568 file. To change the file, make a new shadow password file (the format
569 varies from system to system\-\-see \fBpasswd\fR\|(1) for specifics) and use
570 \&\f(CWpwd_mkdb(8)\fR to install it (see \fBpwd_mkdb\fR\|(8) for more details).
571 .SS "How do I set the time and date?"
572 .IX Subsection "How do I set the time and date?"
573 Assuming you\*(Aqre running under sufficient permissions, you should be
574 able to set the system\-wide date and time by running the \f(CWdate(1)\fR
575 program. (There is no way to set the time and date on a per\-process
576 basis.) This mechanism will work for Unix, MS\-DOS, Windows, and NT;
577 the VMS equivalent is \f(CW\*(C`set time\*(C'\fR.
578 .PP
579 However, if all you want to do is change your time zone, you can
580 probably get away with setting an environment variable:
581 .PP
582 .Vb 3
583 \& $ENV{TZ} = "MST7MDT"; # Unixish
584 \& $ENV{\*(AqSYS$TIMEZONE_DIFFERENTIAL\*(Aq}="\-5" # vms
585 \& system(\*(Aqtrn\*(Aq, \*(Aqcomp.lang.perl.misc\*(Aq);
586 .Ve
587 .SS "How can I \fBsleep()\fP or \fBalarm()\fP for under a second?"
588 .IX Xref "Time::HiRes BSD::Itimer sleep select"
589 .IX Subsection "How can I sleep() or alarm() for under a second?"
590 If you want finer granularity than the 1 second that the \f(CWsleep()\fR
591 function provides, the easiest way is to use the \f(CWselect()\fR function as
592 documented in "select" in perlfunc. Try the Time::HiRes and
593 the BSD::Itimer modules (available from CPAN, and starting from
594 Perl 5.8 Time::HiRes is part of the standard distribution).
595 .SS "How can I measure time under a second?"
596 .IX Xref "Time::HiRes BSD::Itimer sleep select"
597 .IX Subsection "How can I measure time under a second?"
598 (contributed by brian d foy)
599 .PP
600 The Time::HiRes module (part of the standard distribution as of
601 Perl 5.8) measures time with the \f(CWgettimeofday()\fR system call, which
602 returns the time in microseconds since the epoch. If you can\*(Aqt install
603 Time::HiRes for older Perls and you are on a Unixish system, you
604 may be able to call \f(CWgettimeofday(2)\fR directly. See
605 "syscall" in perlfunc.
606 .SS "How can I do an \fBatexit()\fP or \fBsetjmp()\fP/\fBlongjmp()\fP? (Exception handling)"
607 .IX Subsection "How can I do an atexit() or setjmp()/longjmp()? (Exception handling)"
608 You can use the \f(CW\*(C`END\*(C'\fR block to simulate \f(CWatexit()\fR. Each package\*(Aqs
609 \&\f(CW\*(C`END\*(C'\fR block is called when the program or thread ends. See the perlmod
610 manpage for more details about \f(CW\*(C`END\*(C'\fR blocks.
611 .PP
612 For example, you can use this to make sure your filter program managed
613 to finish its output without filling up the disk:
614 .PP
615 .Vb 3
616 \& END {
617 \& close(STDOUT) || die "stdout close failed: $!";
618 \& }
619 .Ve
620 .PP
621 The \f(CW\*(C`END\*(C'\fR block isn\*(Aqt called when untrapped signals kill the program,
622 though, so if you use \f(CW\*(C`END\*(C'\fR blocks you should also use
623 .PP
624 .Vb 1
625 \& use sigtrap qw(die normal\-signals);
626 .Ve
627 .PP
628 Perl\*(Aqs exception\-handling mechanism is its \f(CWeval()\fR operator. You
629 can use \f(CWeval()\fR as \f(CW\*(C`setjmp\*(C'\fR and \f(CWdie()\fR as \f(CW\*(C`longjmp\*(C'\fR. For
630 details of this, see the section on signals, especially the time\-out
631 handler for a blocking \f(CWflock()\fR in "Signals" in perlipc or the
632 section on "Signals" in \fIProgramming Perl\fR.
633 .PP
634 If exception handling is all you\*(Aqre interested in, use one of the
635 many CPAN modules that handle exceptions, such as Try::Tiny.
636 .PP
637 If you want the \f(CWatexit()\fR syntax (and an \f(CWrmexit()\fR as well), try the
638 \&\f(CW\*(C`AtExit\*(C'\fR module available from CPAN.
639 .SS "Why doesn\*(Aqt my sockets program work under System V (Solaris)? What does the error message ""Protocol not supported"" mean?"
640 .IX Subsection "Why doesn't my sockets program work under System V (Solaris)? What does the error message ""Protocol not supported"" mean?"
641 Some Sys\-V based systems, notably Solaris 2.X, redefined some of the
642 standard socket constants. Since these were constant across all
643 architectures, they were often hardwired into perl code. The proper
644 way to deal with this is to "use Socket" to get the correct values.
645 .PP
646 Note that even though SunOS and Solaris are binary compatible, these
647 values are different. Go figure.
648 .SS "How can I call my system\*(Aqs unique C functions from Perl?"
649 .IX Subsection "How can I call my system's unique C functions from Perl?"
650 In most cases, you write an external module to do it\-\-see the answer
651 to "Where can I learn about linking C with Perl? [h2xs, xsubpp]".
652 However, if the function is a system call, and your system supports
653 \&\f(CWsyscall()\fR, you can use the \f(CW\*(C`syscall\*(C'\fR function (documented in
654 perlfunc).
655 .PP
656 Remember to check the modules that came with your distribution, and
657 CPAN as well\-\-someone may already have written a module to do it. On
658 Windows, try Win32::API. On Macs, try Mac::Carbon. If no module
659 has an interface to the C function, you can inline a bit of C in your
660 Perl source with Inline::C.
661 .SS "Where do I get the include files to do \fBioctl()\fP or \fBsyscall()\fP?"
662 .IX Subsection "Where do I get the include files to do ioctl() or syscall()?"
663 Historically, these would be generated by the h2ph tool, part of the
664 standard perl distribution. This program converts \f(CWcpp(1)\fR directives
665 in C header files to files containing subroutine definitions, like
666 \&\f(CWSYS_getitimer()\fR, which you can use as arguments to your functions.
667 It doesn\*(Aqt work perfectly, but it usually gets most of the job done.
668 Simple files like \fIerrno.h\fR, \fIsyscall.h\fR, and \fIsocket.h\fR were fine,
669 but the hard ones like \fIioctl.h\fR nearly always need to be hand\-edited.
670 Here\*(Aqs how to install the *.ph files:
671 .PP
672 .Vb 3
673 \& 1. Become the super\-user
674 \& 2. cd /usr/include
675 \& 3. h2ph *.h */*.h
676 .Ve
677 .PP
678 If your system supports dynamic loading, for reasons of portability and
679 sanity you probably ought to use h2xs (also part of the standard perl
680 distribution). This tool converts C header files to Perl extensions.
681 See perlxstut for how to get started with h2xs.
682 .PP
683 If your system doesn\*(Aqt support dynamic loading, you still probably
684 ought to use h2xs. See perlxstut and ExtUtils::MakeMaker for
685 more information (in brief, just use \fBmake perl\fR instead of a plain
686 \&\fBmake\fR to rebuild perl with a new static extension).
687 .SS "Why do setuid perl scripts complain about kernel problems?"
688 .IX Subsection "Why do setuid perl scripts complain about kernel problems?"
689 Some operating systems have bugs in the kernel that make setuid
690 scripts inherently insecure. Perl gives you a number of options
691 (described in perlsec) to work around such systems.
692 .SS "How can I open a pipe both to and from a command?"
693 .IX Subsection "How can I open a pipe both to and from a command?"
694 The IPC::Open2 module (part of the standard perl distribution) is
695 an easy\-to\-use approach that internally uses \f(CWpipe()\fR, \f(CWfork()\fR, and
696 \&\f(CWexec()\fR to do the job. Make sure you read the deadlock warnings in
697 its documentation, though (see IPC::Open2). See
698 "Bidirectional Communication with Another Process" in perlipc and
699 "Bidirectional Communication with Yourself" in perlipc
700 .PP
701 You may also use the IPC::Open3 module (part of the standard perl
702 distribution), but be warned that it has a different order of
703 arguments from IPC::Open2 (see IPC::Open3).
704 .SS "Why can\*(Aqt I get the output of a command with \fBsystem()\fP?"
705 .IX Subsection "Why can't I get the output of a command with system()?"
706 You\*(Aqre confusing the purpose of \f(CWsystem()\fR and backticks (\`\`). \f(CWsystem()\fR
707 runs a command and returns exit status information (as a 16 bit value:
708 the low 7 bits are the signal the process died from, if any, and
709 the high 8 bits are the actual exit value). Backticks (\`\`) run a
710 command and return what it sent to STDOUT.
711 .PP
712 .Vb 2
713 \& my $exit_status = system("mail\-users");
714 \& my $output_string = \`ls\`;
715 .Ve
716 .SS "How can I capture STDERR from an external command?"
717 .IX Subsection "How can I capture STDERR from an external command?"
718 There are three basic ways of running external commands:
719 .PP
720 .Vb 3
721 \& system $cmd; # using system()
722 \& my $output = \`$cmd\`; # using backticks (\`\`)
723 \& open (my $pipe_fh, "$cmd |"); # using open()
724 .Ve
725 .PP
726 With \f(CWsystem()\fR, both STDOUT and STDERR will go the same place as the
727 script\*(Aqs STDOUT and STDERR, unless the \f(CWsystem()\fR command redirects them.
728 Backticks and \f(CWopen()\fR read \fBonly\fR the STDOUT of your command.
729 .PP
730 You can also use the \f(CWopen3()\fR function from IPC::Open3. Benjamin
731 Goldberg provides some sample code:
732 .PP
733 To capture a program\*(Aqs STDOUT, but discard its STDERR:
734 .PP
735 .Vb 7
736 \& use IPC::Open3;
737 \& use File::Spec;
738 \& my $in = \*(Aq\*(Aq;
739 \& open(NULL, ">", File::Spec\->devnull);
740 \& my $pid = open3($in, \e*PH, ">&NULL", "cmd");
741 \& while( <PH> ) { }
742 \& waitpid($pid, 0);
743 .Ve
744 .PP
745 To capture a program\*(Aqs STDERR, but discard its STDOUT:
746 .PP
747 .Vb 7
748 \& use IPC::Open3;
749 \& use File::Spec;
750 \& my $in = \*(Aq\*(Aq;
751 \& open(NULL, ">", File::Spec\->devnull);
752 \& my $pid = open3($in, ">&NULL", \e*PH, "cmd");
753 \& while( <PH> ) { }
754 \& waitpid($pid, 0);
755 .Ve
756 .PP
757 To capture a program\*(Aqs STDERR, and let its STDOUT go to our own STDERR:
758 .PP
759 .Vb 5
760 \& use IPC::Open3;
761 \& my $in = \*(Aq\*(Aq;
762 \& my $pid = open3($in, ">&STDERR", \e*PH, "cmd");
763 \& while( <PH> ) { }
764 \& waitpid($pid, 0);
765 .Ve
766 .PP
767 To read both a command\*(Aqs STDOUT and its STDERR separately, you can
768 redirect them to temp files, let the command run, then read the temp
769 files:
770 .PP
771 .Vb 10
772 \& use IPC::Open3;
773 \& use IO::File;
774 \& my $in = \*(Aq\*(Aq;
775 \& local *CATCHOUT = IO::File\->new_tmpfile;
776 \& local *CATCHERR = IO::File\->new_tmpfile;
777 \& my $pid = open3($in, ">&CATCHOUT", ">&CATCHERR", "cmd");
778 \& waitpid($pid, 0);
779 \& seek $_, 0, 0 for \e*CATCHOUT, \e*CATCHERR;
780 \& while( <CATCHOUT> ) {}
781 \& while( <CATCHERR> ) {}
782 .Ve
783 .PP
784 But there\*(Aqs no real need for \fBboth\fR to be tempfiles... the following
785 should work just as well, without deadlocking:
786 .PP
787 .Vb 9
788 \& use IPC::Open3;
789 \& my $in = \*(Aq\*(Aq;
790 \& use IO::File;
791 \& local *CATCHERR = IO::File\->new_tmpfile;
792 \& my $pid = open3($in, \e*CATCHOUT, ">&CATCHERR", "cmd");
793 \& while( <CATCHOUT> ) {}
794 \& waitpid($pid, 0);
795 \& seek CATCHERR, 0, 0;
796 \& while( <CATCHERR> ) {}
797 .Ve
798 .PP
799 And it\*(Aqll be faster, too, since we can begin processing the program\*(Aqs
800 stdout immediately, rather than waiting for the program to finish.
801 .PP
802 With any of these, you can change file descriptors before the call:
803 .PP
804 .Vb 2
805 \& open(STDOUT, ">logfile");
806 \& system("ls");
807 .Ve
808 .PP
809 or you can use Bourne shell file\-descriptor redirection:
810 .PP
811 .Vb 2
812 \& $output = \`$cmd 2>some_file\`;
813 \& open (PIPE, "cmd 2>some_file |");
814 .Ve
815 .PP
816 You can also use file\-descriptor redirection to make STDERR a
817 duplicate of STDOUT:
818 .PP
819 .Vb 2
820 \& $output = \`$cmd 2>&1\`;
821 \& open (PIPE, "cmd 2>&1 |");
822 .Ve
823 .PP
824 Note that you \fIcannot\fR simply open STDERR to be a dup of STDOUT
825 in your Perl program and avoid calling the shell to do the redirection.
826 This doesn\*(Aqt work:
827 .PP
828 .Vb 2
829 \& open(STDERR, ">&STDOUT");
830 \& $alloutput = \`cmd args\`; # stderr still escapes
831 .Ve
832 .PP
833 This fails because the \f(CWopen()\fR makes STDERR go to where STDOUT was
834 going at the time of the \f(CWopen()\fR. The backticks then make STDOUT go to
835 a string, but don\*(Aqt change STDERR (which still goes to the old
836 STDOUT).
837 .PP
838 Note that you \fImust\fR use Bourne shell (\f(CWsh(1)\fR) redirection syntax in
839 backticks, not \f(CWcsh(1)\fR! Details on why Perl\*(Aqs \f(CWsystem()\fR and backtick
840 and pipe opens all use the Bourne shell are in the
841 \&\fIversus/csh.whynot\fR article in the "Far More Than You Ever Wanted To
842 Know" collection in <http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> . To
843 capture a command\*(Aqs STDERR and STDOUT together:
844 .PP
845 .Vb 3
846 \& $output = \`cmd 2>&1\`; # either with backticks
847 \& $pid = open(PH, "cmd 2>&1 |"); # or with an open pipe
848 \& while (<PH>) { } # plus a read
849 .Ve
850 .PP
851 To capture a command\*(Aqs STDOUT but discard its STDERR:
852 .PP
853 .Vb 3
854 \& $output = \`cmd 2>/dev/null\`; # either with backticks
855 \& $pid = open(PH, "cmd 2>/dev/null |"); # or with an open pipe
856 \& while (<PH>) { } # plus a read
857 .Ve
858 .PP
859 To capture a command\*(Aqs STDERR but discard its STDOUT:
860 .PP
861 .Vb 3
862 \& $output = \`cmd 2>&1 1>/dev/null\`; # either with backticks
863 \& $pid = open(PH, "cmd 2>&1 1>/dev/null |"); # or with an open pipe
864 \& while (<PH>) { } # plus a read
865 .Ve
866 .PP
867 To exchange a command\*(Aqs STDOUT and STDERR in order to capture the STDERR
868 but leave its STDOUT to come out our old STDERR:
869 .PP
870 .Vb 3
871 \& $output = \`cmd 3>&1 1>&2 2>&3 3>&\-\`; # either with backticks
872 \& $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&\-|");# or with an open pipe
873 \& while (<PH>) { } # plus a read
874 .Ve
875 .PP
876 To read both a command\*(Aqs STDOUT and its STDERR separately, it\*(Aqs easiest
877 to redirect them separately to files, and then read from those files
878 when the program is done:
879 .PP
880 .Vb 1
881 \& system("program args 1>program.stdout 2>program.stderr");
882 .Ve
883 .PP
884 Ordering is important in all these examples. That\*(Aqs because the shell
885 processes file descriptor redirections in strictly left to right order.
886 .PP
887 .Vb 2
888 \& system("prog args 1>tmpfile 2>&1");
889 \& system("prog args 2>&1 1>tmpfile");
890 .Ve
891 .PP
892 The first command sends both standard out and standard error to the
893 temporary file. The second command sends only the old standard output
894 there, and the old standard error shows up on the old standard out.
895 .SS "Why doesn\*(Aqt \fBopen()\fP return an error when a pipe open fails?"
896 .IX Subsection "Why doesn't open() return an error when a pipe open fails?"
897 If the second argument to a piped \f(CWopen()\fR contains shell
898 metacharacters, perl \f(CWfork()\fRs, then \f(CWexec()\fRs a shell to decode the
899 metacharacters and eventually run the desired program. If the program
900 couldn\*(Aqt be run, it\*(Aqs the shell that gets the message, not Perl. All
901 your Perl program can find out is whether the shell itself could be
902 successfully started. You can still capture the shell\*(Aqs STDERR and
903 check it for error messages. See "How can I capture STDERR from an
904 external command?" elsewhere in this document, or use the
905 IPC::Open3 module.
906 .PP
907 If there are no shell metacharacters in the argument of \f(CWopen()\fR, Perl
908 runs the command directly, without using the shell, and can correctly
909 report whether the command started.
910 .SS "What\*(Aqs wrong with using backticks in a void context?"
911 .IX Subsection "What's wrong with using backticks in a void context?"
912 Strictly speaking, nothing. Stylistically speaking, it\*(Aqs not a good
913 way to write maintainable code. Perl has several operators for
914 running external commands. Backticks are one; they collect the output
915 from the command for use in your program. The \f(CW\*(C`system\*(C'\fR function is
916 another; it doesn\*(Aqt do this.
917 .PP
918 Writing backticks in your program sends a clear message to the readers
919 of your code that you wanted to collect the output of the command.
920 Why send a clear message that isn\*(Aqt true?
921 .PP
922 Consider this line:
923 .PP
924 .Vb 1
925 \& \`cat /etc/termcap\`;
926 .Ve
927 .PP
928 You forgot to check \f(CW$?\fR to see whether the program even ran
929 correctly. Even if you wrote
930 .PP
931 .Vb 1
932 \& print \`cat /etc/termcap\`;
933 .Ve
934 .PP
935 this code could and probably should be written as
936 .PP
937 .Vb 2
938 \& system("cat /etc/termcap") == 0
939 \& or die "cat program failed!";
940 .Ve
941 .PP
942 which will echo the cat command\*(Aqs output as it is generated, instead
943 of waiting until the program has completed to print it out. It also
944 checks the return value.
945 .PP
946 \&\f(CW\*(C`system\*(C'\fR also provides direct control over whether shell wildcard
947 processing may take place, whereas backticks do not.
948 .SS "How can I call backticks without shell processing?"
949 .IX Subsection "How can I call backticks without shell processing?"
950 This is a bit tricky. You can\*(Aqt simply write the command
951 like this:
952 .PP
953 .Vb 1
954 \& @ok = \`grep @opts \*(Aq$search_string\*(Aq @filenames\`;
955 .Ve
956 .PP
957 As of Perl 5.8.0, you can use \f(CWopen()\fR with multiple arguments.
958 Just like the list forms of \f(CWsystem()\fR and \f(CWexec()\fR, no shell
959 escapes happen.
960 .PP
961 .Vb 3
962 \& open( GREP, "\-|", \*(Aqgrep\*(Aq, @opts, $search_string, @filenames );
963 \& chomp(@ok = <GREP>);
964 \& close GREP;
965 .Ve
966 .PP
967 You can also:
968 .PP
969 .Vb 10
970 \& my @ok = ();
971 \& if (open(GREP, "\-|")) {
972 \& while (<GREP>) {
973 \& chomp;
974 \& push(@ok, $_);
975 \& }
976 \& close GREP;
977 \& } else {
978 \& exec \*(Aqgrep\*(Aq, @opts, $search_string, @filenames;
979 \& }
980 .Ve
981 .PP
982 Just as with \f(CWsystem()\fR, no shell escapes happen when you \f(CWexec()\fR a
983 list. Further examples of this can be found in "Safe Pipe
984 Opens" in perlipc.
985 .PP
986 Note that if you\*(Aqre using Windows, no solution to this vexing issue is
987 even possible. Even though Perl emulates \f(CWfork()\fR, you\*(Aqll still be
988 stuck, because Windows does not have an argc/argv\-style API.
989 .SS "Why can\*(Aqt my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS\-DOS)?"
990 .IX Subsection "Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?"
991 This happens only if your perl is compiled to use stdio instead of
992 perlio, which is the default. Some (maybe all?) stdios set error and
993 eof flags that you may need to clear. The POSIX module defines
994 \&\f(CWclearerr()\fR that you can use. That is the technically correct way to
995 do it. Here are some less reliable workarounds:
996 .IP 1. 4
997 Try keeping around the seekpointer and go there, like this:
998 .Sp
999 .Vb 2
1000 \& my $where = tell($log_fh);
1001 \& seek($log_fh, $where, 0);
1002 .Ve
1003 .IP 2. 4
1004 If that doesn\*(Aqt work, try seeking to a different part of the file and
1005 then back.
1006 .IP 3. 4
1007 If that doesn\*(Aqt work, try seeking to a different part of
1008 the file, reading something, and then seeking back.
1009 .IP 4. 4
1010 If that doesn\*(Aqt work, give up on your stdio package and use sysread.
1011 .SS "How can I convert my shell script to perl?"
1012 .IX Subsection "How can I convert my shell script to perl?"
1013 Learn Perl and rewrite it. Seriously, there\*(Aqs no simple converter.
1014 Things that are awkward to do in the shell are easy to do in Perl, and
1015 this very awkwardness is what would make a shell\->perl converter
1016 nigh\-on impossible to write. By rewriting it, you\*(Aqll think about what
1017 you\*(Aqre really trying to do, and hopefully will escape the shell\*(Aqs
1018 pipeline datastream paradigm, which while convenient for some matters,
1019 causes many inefficiencies.
1020 .SS "Can I use perl to run a telnet or ftp session?"
1021 .IX Subsection "Can I use perl to run a telnet or ftp session?"
1022 Try the Net::FTP and Net::Telnet modules (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\*(Aqt 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\*(Aqt 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\*(Aqs 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\*(Aqre 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\*(Aqt 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\*(Aqt 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\*(Aqt 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\*(Aqs output in your shell; check out the
1077 comp.unix.questions FAQ for details.
1078 .SS "How do I close a process\*(Aqs 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\*(Aqs 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\*(Aqs 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\|(4)
1091 for details. Or better yet, you can just use the \f(CWPOSIX::setsid()\fR
1092 function, so you don\*(Aqt 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\*(Aqre 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\*(Aqm 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\*(Aqt 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\*(Aqt. 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\*(Aqre 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\*(Aqt see that "Perl:", it\*(Aqs 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\*(Aqt. However, they
1285 all should be in the perldiag manpage. If you don\*(Aqt find the error in
1286 there, it probably isn\*(Aqt 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\*(Aqs 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\*(Aqt get a paragraph or two of expanded discussion, it
1297 might not be perl\*(Aqs 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\*(Aqs 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\*(Aqs 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\*(Aqt 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\*(Aqs 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\*(Aqs 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 \*(Aqpm\*(Aq 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\*(Aqs 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.