Imported upstream version 1.5
[manpages-zh.git] / raw / man1 / perlfaq8.1
blobc387375da716b0d099125ed043937e4e7d9b020f
1 .\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14
2 .\"
3 .\" Standard preamble:
4 .\" ========================================================================
5 .de Sh \" Subsection heading
6 .br
7 .if t .Sp
8 .ne 5
9 .PP
10 \fB\\$1\fR
11 .PP
13 .de Sp \" Vertical space (when we can't use .PP)
14 .if t .sp .5v
15 .if n .sp
17 .de Vb \" Begin verbatim text
18 .ft CW
19 .nf
20 .ne \\$1
22 .de Ve \" End verbatim text
23 .ft R
24 .fi
26 .\" Set up some character translations and predefined strings.  \*(-- will
27 .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28 .\" double quote, and \*(R" will give a right double quote.  | will give a
29 .\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
30 .\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
31 .\" expand to `' in nroff, nothing in troff, for use with C<>.
32 .tr \(*W-|\(bv\*(Tr
33 .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34 .ie n \{\
35 .    ds -- \(*W-
36 .    ds PI pi
37 .    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38 .    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
39 .    ds L" ""
40 .    ds R" ""
41 .    ds C` ""
42 .    ds C' ""
43 'br\}
44 .el\{\
45 .    ds -- \|\(em\|
46 .    ds PI \(*p
47 .    ds L" ``
48 .    ds R" ''
49 'br\}
50 .\"
51 .\" If the F register is turned on, we'll generate index entries on stderr for
52 .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53 .\" entries marked with X<> in POD.  Of course, you'll have to process the
54 .\" output yourself in some meaningful fashion.
55 .if \nF \{\
56 .    de IX
57 .    tm Index:\\$1\t\\n%\t"\\$2"
59 .    nr % 0
60 .    rr F
61 .\}
62 .\"
63 .\" For nroff, turn off justification.  Always turn off hyphenation; it makes
64 .\" way too many mistakes in technical documents.
65 .hy 0
66 .if n .na
67 .\"
68 .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69 .\" Fear.  Run.  Save yourself.  No user-serviceable parts.
70 .    \" fudge factors for nroff and troff
71 .if n \{\
72 .    ds #H 0
73 .    ds #V .8m
74 .    ds #F .3m
75 .    ds #[ \f1
76 .    ds #] \fP
77 .\}
78 .if t \{\
79 .    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80 .    ds #V .6m
81 .    ds #F 0
82 .    ds #[ \&
83 .    ds #] \&
84 .\}
85 .    \" simple accents for nroff and troff
86 .if n \{\
87 .    ds ' \&
88 .    ds ` \&
89 .    ds ^ \&
90 .    ds , \&
91 .    ds ~ ~
92 .    ds /
93 .\}
94 .if t \{\
95 .    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96 .    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97 .    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98 .    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99 .    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100 .    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
102 .    \" troff and (daisy-wheel) nroff accents
103 .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104 .ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105 .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106 .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107 .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108 .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109 .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110 .ds ae a\h'-(\w'a'u*4/10)'e
111 .ds Ae A\h'-(\w'A'u*4/10)'E
112 .    \" corrections for vroff
113 .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114 .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115 .    \" for low resolution devices (crt and lpr)
116 .if \n(.H>23 .if \n(.V>19 \
118 .    ds : e
119 .    ds 8 ss
120 .    ds o a
121 .    ds d- d\h'-1'\(ga
122 .    ds D- D\h'-1'\(hy
123 .    ds th \o'bp'
124 .    ds Th \o'LP'
125 .    ds ae ae
126 .    ds Ae AE
128 .rm #[ #] #H #V #F C
129 .\" ========================================================================
131 .IX Title "PERLFAQ8 1"
132 .TH PERLFAQ8 1 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide"
133 .SH "NAME"
134 perlfaq8 \- System Interaction ($Revision: 1.1 $, $Date: 2004/06/16 12:41:53 $)
135 .SH "DESCRIPTION"
136 .IX Header "DESCRIPTION"
137 This section of the Perl \s-1FAQ\s0 covers questions involving operating
138 system interaction.  Topics include interprocess communication (\s-1IPC\s0),
139 control over the user-interface (keyboard, screen and pointing
140 devices), and most anything else not related to data manipulation.
142 Read the FAQs and documentation specific to the port of perl to your
143 operating system (eg, perlvms, perlplan9, ...).  These should
144 contain more detailed information on the vagaries of your perl.
145 .Sh "How do I find out which operating system I'm running under?"
146 .IX Subsection "How do I find out which operating system I'm running under?"
147 The $^O variable ($OSNAME if you use English) contains an indication of
148 the name of the operating system (not its release number) that your perl
149 binary was built for.
150 .Sh "How come \fIexec()\fP doesn't return?"
151 .IX Subsection "How come exec() doesn't return?"
152 Because that's what it does: it replaces your currently running
153 program with a different one.  If you want to keep going (as is
154 probably the case if you're asking this question) use \fIsystem()\fR
155 instead.
156 .Sh "How do I do fancy stuff with the keyboard/screen/mouse?"
157 .IX Subsection "How do I do fancy stuff with the keyboard/screen/mouse?"
158 How you access/control keyboards, screens, and pointing devices
159 (\*(L"mice\*(R") is system\-dependent.  Try the following modules:
160 .IP "Keyboard" 4
161 .IX Item "Keyboard"
162 .Vb 5
163 \&    Term::Cap                   Standard perl distribution
164 \&    Term::ReadKey               CPAN
165 \&    Term::ReadLine::Gnu         CPAN
166 \&    Term::ReadLine::Perl        CPAN
167 \&    Term::Screen                CPAN
169 .IP "Screen" 4
170 .IX Item "Screen"
171 .Vb 3
172 \&    Term::Cap                   Standard perl distribution
173 \&    Curses                      CPAN
174 \&    Term::ANSIColor             CPAN
176 .IP "Mouse" 4
177 .IX Item "Mouse"
178 .Vb 1
179 \&    Tk                          CPAN
182 Some of these specific cases are shown below.
183 .Sh "How do I print something out in color?"
184 .IX Subsection "How do I print something out in color?"
185 In general, you don't, because you don't know whether
186 the recipient has a color-aware display device.  If you
187 know that they have an \s-1ANSI\s0 terminal that understands
188 color, you can use the Term::ANSIColor module from \s-1CPAN:\s0
190 .Vb 3
191 \&    use Term::ANSIColor;
192 \&    print color("red"), "Stop!\en", color("reset");
193 \&    print color("green"), "Go!\en", color("reset");
196 Or like this:
198 .Vb 3
199 \&    use Term::ANSIColor qw(:constants);
200 \&    print RED, "Stop!\en", RESET;
201 \&    print GREEN, "Go!\en", RESET;
203 .Sh "How do I read just one key without waiting for a return key?"
204 .IX Subsection "How do I read just one key without waiting for a return key?"
205 Controlling input buffering is a remarkably system-dependent matter.
206 On many systems, you can just use the \fBstty\fR command as shown in
207 \&\*(L"getc\*(R" in perlfunc, but as you see, that's already getting you into
208 portability snags.
210 .Vb 6
211 \&    open(TTY, "+</dev/tty") or die "no tty: $!";
212 \&    system "stty  cbreak </dev/tty >/dev/tty 2>&1";
213 \&    $key = getc(TTY);           # perhaps this works
214 \&    # OR ELSE
215 \&    sysread(TTY, $key, 1);      # probably this does
216 \&    system "stty -cbreak </dev/tty >/dev/tty 2>&1";
219 The Term::ReadKey module from \s-1CPAN\s0 offers an easy-to-use interface that
220 should be more efficient than shelling out to \fBstty\fR for each key.
221 It even includes limited support for Windows.
223 .Vb 4
224 \&    use Term::ReadKey;
225 \&    ReadMode('cbreak');
226 \&    $key = ReadKey(0);
227 \&    ReadMode('normal');
230 However, using the code requires that you have a working C compiler
231 and can use it to build and install a \s-1CPAN\s0 module.  Here's a solution
232 using the standard \s-1POSIX\s0 module, which is already on your systems
233 (assuming your system supports \s-1POSIX\s0).
235 .Vb 2
236 \&    use HotKey;
237 \&    $key = readkey();
240 And here's the HotKey module, which hides the somewhat mystifying calls
241 to manipulate the \s-1POSIX\s0 termios structures.
243 .Vb 2
244 \&    # HotKey.pm
245 \&    package HotKey;
248 .Vb 2
249 \&    @ISA = qw(Exporter);
250 \&    @EXPORT = qw(cbreak cooked readkey);
253 .Vb 3
254 \&    use strict;
255 \&    use POSIX qw(:termios_h);
256 \&    my ($term, $oterm, $echo, $noecho, $fd_stdin);
259 .Vb 4
260 \&    $fd_stdin = fileno(STDIN);
261 \&    $term     = POSIX::Termios->new();
262 \&    $term->getattr($fd_stdin);
263 \&    $oterm     = $term->getlflag();
266 .Vb 2
267 \&    $echo     = ECHO | ECHOK | ICANON;
268 \&    $noecho   = $oterm & ~$echo;
271 .Vb 5
272 \&    sub cbreak {
273 \&        $term->setlflag($noecho);  # ok, so i don't want echo either
274 \&        $term->setcc(VTIME, 1);
275 \&        $term->setattr($fd_stdin, TCSANOW);
276 \&    }
279 .Vb 5
280 \&    sub cooked {
281 \&        $term->setlflag($oterm);
282 \&        $term->setcc(VTIME, 0);
283 \&        $term->setattr($fd_stdin, TCSANOW);
284 \&    }
287 .Vb 7
288 \&    sub readkey {
289 \&        my $key = '';
290 \&        cbreak();
291 \&        sysread(STDIN, $key, 1);
292 \&        cooked();
293 \&        return $key;
294 \&    }
297 .Vb 1
298 \&    END { cooked() }
301 .Vb 1
302 \&    1;
304 .Sh "How do I check whether input is ready on the keyboard?"
305 .IX Subsection "How do I check whether input is ready on the keyboard?"
306 The easiest way to do this is to read a key in nonblocking mode with the
307 Term::ReadKey module from \s-1CPAN\s0, passing it an argument of \-1 to indicate
308 not to block:
310 .Vb 1
311 \&    use Term::ReadKey;
314 .Vb 1
315 \&    ReadMode('cbreak');
318 .Vb 5
319 \&    if (defined ($char = ReadKey(-1)) ) {
320 \&        # input was waiting and it was $char
321 \&    } else {
322 \&        # no input was waiting
323 \&    }
326 .Vb 1
327 \&    ReadMode('normal');                  # restore normal tty settings
329 .Sh "How do I clear the screen?"
330 .IX Subsection "How do I clear the screen?"
331 If you only have do so infrequently, use \f(CW\*(C`system\*(C'\fR:
333 .Vb 1
334 \&    system("clear");
337 If you have to do this a lot, save the clear string
338 so you can print it 100 times without calling a program
339 100 times:
341 .Vb 2
342 \&    $clear_string = `clear`;
343 \&    print $clear_string;
346 If you're planning on doing other screen manipulations, like cursor
347 positions, etc, you might wish to use Term::Cap module:
349 .Vb 3
350 \&    use Term::Cap;
351 \&    $terminal = Term::Cap->Tgetent( {OSPEED => 9600} );
352 \&    $clear_string = $terminal->Tputs('cl');
354 .Sh "How do I get the screen size?"
355 .IX Subsection "How do I get the screen size?"
356 If you have Term::ReadKey module installed from \s-1CPAN\s0,
357 you can use it to fetch the width and height in characters
358 and in pixels:
360 .Vb 2
361 \&    use Term::ReadKey;
362 \&    ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
365 This is more portable than the raw \f(CW\*(C`ioctl\*(C'\fR, but not as
366 illustrative:
368 .Vb 10
369 \&    require 'sys/ioctl.ph';
370 \&    die "no TIOCGWINSZ " unless defined &TIOCGWINSZ;
371 \&    open(TTY, "+</dev/tty")                     or die "No tty: $!";
372 \&    unless (ioctl(TTY, &TIOCGWINSZ, $winsize='')) {
373 \&        die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\en", &TIOCGWINSZ;
374 \&    }
375 \&    ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);
376 \&    print "(row,col) = ($row,$col)";
377 \&    print "  (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
378 \&    print "\en";
380 .Sh "How do I ask the user for a password?"
381 .IX Subsection "How do I ask the user for a password?"
382 (This question has nothing to do with the web.  See a different
383 \&\s-1FAQ\s0 for that.)
385 There's an example of this in \*(L"crypt\*(R" in perlfunc).  First, you put the
386 terminal into \*(L"no echo\*(R" mode, then just read the password normally.
387 You may do this with an old-style \fIioctl()\fR function, \s-1POSIX\s0 terminal
388 control (see \s-1POSIX\s0 or its documentation the Camel Book), or a call
389 to the \fBstty\fR program, with varying degrees of portability.
391 You can also do this for most systems using the Term::ReadKey module
392 from \s-1CPAN\s0, which is easier to use and in theory more portable.
394 .Vb 1
395 \&    use Term::ReadKey;
398 .Vb 2
399 \&    ReadMode('noecho');
400 \&    $password = ReadLine(0);
402 .Sh "How do I read and write the serial port?"
403 .IX Subsection "How do I read and write the serial port?"
404 This depends on which operating system your program is running on.  In
405 the case of Unix, the serial ports will be accessible through files in
406 /dev; on other systems, device names will doubtless differ.
407 Several problem areas common to all device interaction are the
408 following:
409 .IP "lockfiles" 4
410 .IX Item "lockfiles"
411 Your system may use lockfiles to control multiple access.  Make sure
412 you follow the correct protocol.  Unpredictable behavior can result
413 from multiple processes reading from one device.
414 .IP "open mode" 4
415 .IX Item "open mode"
416 If you expect to use both read and write operations on the device,
417 you'll have to open it for update (see \*(L"open\*(R" in perlfunc for
418 details).  You may wish to open it without running the risk of
419 blocking by using \fIsysopen()\fR and \f(CW\*(C`O_RDWR|O_NDELAY|O_NOCTTY\*(C'\fR from the
420 Fcntl module (part of the standard perl distribution).  See
421 \&\*(L"sysopen\*(R" in perlfunc for more on this approach.
422 .IP "end of line" 4
423 .IX Item "end of line"
424 Some devices will be expecting a \*(L"\er\*(R" at the end of each line rather
425 than a \*(L"\en\*(R".  In some ports of perl, \*(L"\er\*(R" and \*(L"\en\*(R" are different from
426 their usual (Unix) \s-1ASCII\s0 values of \*(L"\e012\*(R" and \*(L"\e015\*(R".  You may have to
427 give the numeric values you want directly, using octal (\*(L"\e015\*(R"), hex
428 (\*(L"0x0D\*(R"), or as a control-character specification (\*(L"\ecM\*(R").
430 .Vb 2
431 \&    print DEV "atv1\e012";       # wrong, for some devices
432 \&    print DEV "atv1\e015";       # right, for some devices
435 Even though with normal text files a \*(L"\en\*(R" will do the trick, there is
436 still no unified scheme for terminating a line that is portable
437 between Unix, DOS/Win, and Macintosh, except to terminate \fI\s-1ALL\s0\fR line
438 ends with \*(L"\e015\e012\*(R", and strip what you don't need from the output.
439 This applies especially to socket I/O and autoflushing, discussed
440 next.
441 .IP "flushing output" 4
442 .IX Item "flushing output"
443 If you expect characters to get to your device when you \fIprint()\fR them,
444 you'll want to autoflush that filehandle.  You can use \fIselect()\fR
445 and the \f(CW$|\fR variable to control autoflushing (see "$|" in perlvar
446 and \*(L"select\*(R" in perlfunc, or perlfaq5, ``How do I flush/unbuffer an
447 output filehandle?  Why must I do this?''):
449 .Vb 3
450 \&    $oldh = select(DEV);
451 \&    $| = 1;
452 \&    select($oldh);
455 You'll also see code that does this without a temporary variable, as in
457 .Vb 1
458 \&    select((select(DEV), $| = 1)[0]);
461 Or if you don't mind pulling in a few thousand lines
462 of code just because you're afraid of a little $| variable:
464 .Vb 2
465 \&    use IO::Handle;
466 \&    DEV->autoflush(1);
469 As mentioned in the previous item, this still doesn't work when using
470 socket I/O between Unix and Macintosh.  You'll need to hard code your
471 line terminators, in that case.
472 .IP "non-blocking input" 4
473 .IX Item "non-blocking input"
474 If you are doing a blocking \fIread()\fR or \fIsysread()\fR, you'll have to
475 arrange for an alarm handler to provide a timeout (see
476 \&\*(L"alarm\*(R" in perlfunc).  If you have a non-blocking open, you'll likely
477 have a non-blocking read, which means you may have to use a 4\-arg
478 \&\fIselect()\fR to determine whether I/O is ready on that device (see
479 \&\*(L"select\*(R" in perlfunc.
481 While trying to read from his caller-id box, the notorious Jamie Zawinski
482 <jwz@netscape.com>, after much gnashing of teeth and fighting with sysread,
483 sysopen, \s-1POSIX\s0's tcgetattr business, and various other functions that
484 go bump in the night, finally came up with this:
486 .Vb 13
487 \&    sub open_modem {
488 \&        use IPC::Open2;
489 \&        my $stty = `/bin/stty -g`;
490 \&        open2( \e*MODEM_IN, \e*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
491 \&        # starting cu hoses /dev/tty's stty settings, even when it has
492 \&        # been opened on a pipe...
493 \&        system("/bin/stty $stty");
494 \&        $_ = <MODEM_IN>;
495 \&        chomp;
496 \&        if ( !m/^Connected/ ) {
497 \&            print STDERR "$0: cu printed `$_' instead of `Connected'\en";
498 \&        }
499 \&    }
501 .Sh "How do I decode encrypted password files?"
502 .IX Subsection "How do I decode encrypted password files?"
503 You spend lots and lots of money on dedicated hardware, but this is
504 bound to get you talked about.
506 Seriously, you can't if they are Unix password files\*(--the Unix
507 password system employs one-way encryption.  It's more like hashing than
508 encryption.  The best you can check is whether something else hashes to
509 the same string.  You can't turn a hash back into the original string.
510 Programs like Crack
511 can forcibly (and intelligently) try to guess passwords, but don't
512 (can't) guarantee quick success.
514 If you're worried about users selecting bad passwords, you should
515 proactively check when they try to change their password (by modifying
516 \&\fIpasswd\fR\|(1), for example).
517 .Sh "How do I start a process in the background?"
518 .IX Subsection "How do I start a process in the background?"
519 Several modules can start other processes that do not block
520 your Perl program.  You can use IPC::Open3, Parallel::Jobs,
521 IPC::Run, and some of the \s-1POE\s0 modules.  See \s-1CPAN\s0 for more
522 details.
524 You could also use
526 .Vb 1
527 \&    system("cmd &")
530 or you could use fork as documented in \*(L"fork\*(R" in perlfunc, with
531 further examples in perlipc.  Some things to be aware of, if you're
532 on a Unix-like system:
533 .IP "\s-1STDIN\s0, \s-1STDOUT\s0, and \s-1STDERR\s0 are shared" 4
534 .IX Item "STDIN, STDOUT, and STDERR are shared"
535 Both the main process and the backgrounded one (the \*(L"child\*(R" process)
536 share the same \s-1STDIN\s0, \s-1STDOUT\s0 and \s-1STDERR\s0 filehandles.  If both try to
537 access them at once, strange things can happen.  You may want to close
538 or reopen these for the child.  You can get around this with
539 \&\f(CW\*(C`open\*(C'\fRing a pipe (see \*(L"open\*(R" in perlfunc) but on some systems this
540 means that the child process cannot outlive the parent.
541 .IP "Signals" 4
542 .IX Item "Signals"
543 You'll have to catch the \s-1SIGCHLD\s0 signal, and possibly \s-1SIGPIPE\s0 too.
544 \&\s-1SIGCHLD\s0 is sent when the backgrounded process finishes.  \s-1SIGPIPE\s0 is
545 sent when you write to a filehandle whose child process has closed (an
546 untrapped \s-1SIGPIPE\s0 can cause your program to silently die).  This is
547 not an issue with \f(CW\*(C`system("cmd&")\*(C'\fR.
548 .IP "Zombies" 4
549 .IX Item "Zombies"
550 You have to be prepared to \*(L"reap\*(R" the child process when it finishes.
552 .Vb 1
553 \&    $SIG{CHLD} = sub { wait };
556 .Vb 1
557 \&    $SIG{CHLD} = 'IGNORE';
560 You can also use a double fork. You immediately \fIwait()\fR for your
561 first child, and the init daemon will \fIwait()\fR for your grandchild once
562 it exits.
564 .Vb 8
565 \&        unless ($pid = fork) {
566 \&                unless (fork) {
567 \&            exec "what you really wanna do";
568 \&            die "exec failed!";
569 \&                }
570 \&        exit 0;
571 \&        }
572 \&    waitpid($pid,0);
575 See \*(L"Signals\*(R" in perlipc for other examples of code to do this.
576 Zombies are not an issue with \f(CW\*(C`system("prog &")\*(C'\fR.
577 .Sh "How do I trap control characters/signals?"
578 .IX Subsection "How do I trap control characters/signals?"
579 You don't actually \*(L"trap\*(R" a control character.  Instead, that character
580 generates a signal which is sent to your terminal's currently
581 foregrounded process group, which you then trap in your process.
582 Signals are documented in \*(L"Signals\*(R" in perlipc and the
583 section on ``Signals'' in the Camel.
585 Be warned that very few C libraries are re\-entrant.  Therefore, if you
586 attempt to \fIprint()\fR in a handler that got invoked during another stdio
587 operation your internal structures will likely be in an
588 inconsistent state, and your program will dump core.  You can
589 sometimes avoid this by using \fIsyswrite()\fR instead of \fIprint()\fR.
591 Unless you're exceedingly careful, the only safe things to do inside a
592 signal handler are (1) set a variable and (2) exit.  In the first case,
593 you should only set a variable in such a way that \fImalloc()\fR is not
594 called (eg, by setting a variable that already has a value).
596 For example:
598 .Vb 5
599 \&    $Interrupted = 0;   # to ensure it has a value
600 \&    $SIG{INT} = sub {
601 \&        $Interrupted++;
602 \&        syswrite(STDERR, "ouch\en", 5);
603 \&    }
606 However, because syscalls restart by default, you'll find that if
607 you're in a \*(L"slow\*(R" call, such as <\s-1FH\s0>, \fIread()\fR, \fIconnect()\fR, or
608 \&\fIwait()\fR, that the only way to terminate them is by \*(L"longjumping\*(R" out;
609 that is, by raising an exception.  See the time-out handler for a
610 blocking \fIflock()\fR in \*(L"Signals\*(R" in perlipc or the section on ``Signals''
611 in the Camel book.
612 .Sh "How do I modify the shadow password file on a Unix system?"
613 .IX Subsection "How do I modify the shadow password file on a Unix system?"
614 If perl was installed correctly and your shadow library was written
615 properly, the getpw*() functions described in perlfunc should in
616 theory provide (read\-only) access to entries in the shadow password
617 file.  To change the file, make a new shadow password file (the format
618 varies from system to system\*(--see passwd for specifics) and use
619 \&\fIpwd_mkdb\fR\|(8) to install it (see pwd_mkdb for more details).
620 .Sh "How do I set the time and date?"
621 .IX Subsection "How do I set the time and date?"
622 Assuming you're running under sufficient permissions, you should be
623 able to set the system-wide date and time by running the \fIdate\fR\|(1)
624 program.  (There is no way to set the time and date on a per-process
625 basis.)  This mechanism will work for Unix, \s-1MS\-DOS\s0, Windows, and \s-1NT\s0;
626 the \s-1VMS\s0 equivalent is \f(CW\*(C`set time\*(C'\fR.
628 However, if all you want to do is change your time zone, you can
629 probably get away with setting an environment variable:
631 .Vb 3
632 \&    $ENV{TZ} = "MST7MDT";                  # unixish
633 \&    $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
634 \&    system "trn comp.lang.perl.misc";
636 .Sh "How can I \fIsleep()\fP or \fIalarm()\fP for under a second?"
637 .IX Subsection "How can I sleep() or alarm() for under a second?"
638 If you want finer granularity than the 1 second that the \fIsleep()\fR
639 function provides, the easiest way is to use the \fIselect()\fR function as
640 documented in \*(L"select\*(R" in perlfunc.  Try the Time::HiRes and
641 the BSD::Itimer modules (available from \s-1CPAN\s0, and starting from
642 Perl 5.8 Time::HiRes is part of the standard distribution).
643 .Sh "How can I measure time under a second?"
644 .IX Subsection "How can I measure time under a second?"
645 In general, you may not be able to.  The Time::HiRes module (available
646 from \s-1CPAN\s0, and starting from Perl 5.8 part of the standard distribution)
647 provides this functionality for some systems.
649 If your system supports both the \fIsyscall()\fR function in Perl as well as
650 a system call like \fIgettimeofday\fR\|(2), then you may be able to do
651 something like this:
653 .Vb 1
654 \&    require 'sys/syscall.ph';
657 .Vb 1
658 \&    $TIMEVAL_T = "LL";
661 .Vb 1
662 \&    $done = $start = pack($TIMEVAL_T, ());
665 .Vb 2
666 \&    syscall(&SYS_gettimeofday, $start, 0) != -1
667 \&               or die "gettimeofday: $!";
670 .Vb 3
671 \&       ##########################
672 \&       # DO YOUR OPERATION HERE #
673 \&       ##########################
676 .Vb 2
677 \&    syscall( &SYS_gettimeofday, $done, 0) != -1
678 \&           or die "gettimeofday: $!";
681 .Vb 2
682 \&    @start = unpack($TIMEVAL_T, $start);
683 \&    @done  = unpack($TIMEVAL_T, $done);
686 .Vb 2
687 \&    # fix microseconds
688 \&    for ($done[1], $start[1]) { $_ /= 1_000_000 }
691 .Vb 3
692 \&    $delta_time = sprintf "%.4f", ($done[0]  + $done[1]  )
693 \&                                            -
694 \&                                 ($start[0] + $start[1] );
696 .Sh "How can I do an \fIatexit()\fP or \fIsetjmp()\fP/\fIlongjmp()\fP? (Exception handling)"
697 .IX Subsection "How can I do an atexit() or setjmp()/longjmp()? (Exception handling)"
698 Release 5 of Perl added the \s-1END\s0 block, which can be used to simulate
699 \&\fIatexit()\fR.  Each package's \s-1END\s0 block is called when the program or
700 thread ends (see perlmod manpage for more details).
702 For example, you can use this to make sure your filter program
703 managed to finish its output without filling up the disk:
705 .Vb 3
706 \&    END {
707 \&        close(STDOUT) || die "stdout close failed: $!";
708 \&    }
711 The \s-1END\s0 block isn't called when untrapped signals kill the program,
712 though, so if you use \s-1END\s0 blocks you should also use
714 .Vb 1
715 \&        use sigtrap qw(die normal-signals);
718 Perl's exception-handling mechanism is its \fIeval()\fR operator.  You can
719 use \fIeval()\fR as setjmp and \fIdie()\fR as longjmp.  For details of this, see
720 the section on signals, especially the time-out handler for a blocking
721 \&\fIflock()\fR in \*(L"Signals\*(R" in perlipc or the section on ``Signals'' in
722 the Camel Book.
724 If exception handling is all you're interested in, try the
725 exceptions.pl library (part of the standard perl distribution).
727 If you want the \fIatexit()\fR syntax (and an \fIrmexit()\fR as well), try the
728 AtExit module available from \s-1CPAN\s0.
729 .ie n .Sh "Why doesn't my sockets program work under System V (Solaris)?  What does the error message ""Protocol not supported"" mean?"
730 .el .Sh "Why doesn't my sockets program work under System V (Solaris)?  What does the error message ``Protocol not supported'' mean?"
731 .IX Subsection "Why doesn't my sockets program work under System V (Solaris)?  What does the error message Protocol not supported mean?"
732 Some Sys-V based systems, notably Solaris 2.X, redefined some of the
733 standard socket constants.  Since these were constant across all
734 architectures, they were often hardwired into perl code.  The proper
735 way to deal with this is to \*(L"use Socket\*(R" to get the correct values.
737 Note that even though SunOS and Solaris are binary compatible, these
738 values are different.  Go figure.
739 .Sh "How can I call my system's unique C functions from Perl?"
740 .IX Subsection "How can I call my system's unique C functions from Perl?"
741 In most cases, you write an external module to do it\*(--see the answer
742 to \*(L"Where can I learn about linking C with Perl? [h2xs, xsubpp]\*(R".
743 However, if the function is a system call, and your system supports
744 \&\fIsyscall()\fR, you can use the syscall function (documented in
745 perlfunc).
747 Remember to check the modules that came with your distribution, and
748 \&\s-1CPAN\s0 as well\-\-\-someone may already have written a module to do it. On
749 Windows, try Win32::API.  On Macs, try Mac::Carbon.  If no module
750 has an interface to the C function, you can inline a bit of C in your
751 Perl source with Inline::C.
752 .Sh "Where do I get the include files to do \fIioctl()\fP or \fIsyscall()\fP?"
753 .IX Subsection "Where do I get the include files to do ioctl() or syscall()?"
754 Historically, these would be generated by the h2ph tool, part of the
755 standard perl distribution.  This program converts \fIcpp\fR\|(1) directives
756 in C header files to files containing subroutine definitions, like
757 &SYS_getitimer, which you can use as arguments to your functions.
758 It doesn't work perfectly, but it usually gets most of the job done.
759 Simple files like \fIerrno.h\fR, \fIsyscall.h\fR, and \fIsocket.h\fR were fine,
760 but the hard ones like \fIioctl.h\fR nearly always need to hand\-edited.
761 Here's how to install the *.ph files:
763 .Vb 3
764 \&    1.  become super-user
765 \&    2.  cd /usr/include
766 \&    3.  h2ph *.h */*.h
769 If your system supports dynamic loading, for reasons of portability and
770 sanity you probably ought to use h2xs (also part of the standard perl
771 distribution).  This tool converts C header files to Perl extensions.
772 See perlxstut for how to get started with h2xs.
774 If your system doesn't support dynamic loading, you still probably
775 ought to use h2xs.  See perlxstut and ExtUtils::MakeMaker for
776 more information (in brief, just use \fBmake perl\fR instead of a plain
777 \&\fBmake\fR to rebuild perl with a new static extension).
778 .Sh "Why do setuid perl scripts complain about kernel problems?"
779 .IX Subsection "Why do setuid perl scripts complain about kernel problems?"
780 Some operating systems have bugs in the kernel that make setuid
781 scripts inherently insecure.  Perl gives you a number of options
782 (described in perlsec) to work around such systems.
783 .Sh "How can I open a pipe both to and from a command?"
784 .IX Subsection "How can I open a pipe both to and from a command?"
785 The IPC::Open2 module (part of the standard perl distribution) is an
786 easy-to-use approach that internally uses \fIpipe()\fR, \fIfork()\fR, and \fIexec()\fR to do
787 the job.  Make sure you read the deadlock warnings in its documentation,
788 though (see IPC::Open2).  See
789 \&\*(L"Bidirectional Communication with Another Process\*(R" in perlipc and
790 \&\*(L"Bidirectional Communication with Yourself\*(R" in perlipc
792 You may also use the IPC::Open3 module (part of the standard perl
793 distribution), but be warned that it has a different order of
794 arguments from IPC::Open2 (see IPC::Open3).
795 .Sh "Why can't I get the output of a command with \fIsystem()\fP?"
796 .IX Subsection "Why can't I get the output of a command with system()?"
797 You're confusing the purpose of \fIsystem()\fR and backticks (``).  \fIsystem()\fR
798 runs a command and returns exit status information (as a 16 bit value:
799 the low 7 bits are the signal the process died from, if any, and
800 the high 8 bits are the actual exit value).  Backticks (``) run a
801 command and return what it sent to \s-1STDOUT\s0.
803 .Vb 2
804 \&    $exit_status   = system("mail-users");
805 \&    $output_string = `ls`;
807 .Sh "How can I capture \s-1STDERR\s0 from an external command?"
808 .IX Subsection "How can I capture STDERR from an external command?"
809 There are three basic ways of running external commands:
811 .Vb 3
812 \&    system $cmd;                # using system()
813 \&    $output = `$cmd`;           # using backticks (``)
814 \&    open (PIPE, "cmd |");       # using open()
817 With \fIsystem()\fR, both \s-1STDOUT\s0 and \s-1STDERR\s0 will go the same place as the
818 script's \s-1STDOUT\s0 and \s-1STDERR\s0, unless the \fIsystem()\fR command redirects them.
819 Backticks and \fIopen()\fR read \fBonly\fR the \s-1STDOUT\s0 of your command.
821 You can also use the \fIopen3()\fR function from IPC::Open3.  Benjamin
822 Goldberg provides some sample code:
824 To capture a program's \s-1STDOUT\s0, but discard its \s-1STDERR:\s0
826 .Vb 7
827 \&    use IPC::Open3;
828 \&    use File::Spec;
829 \&    use Symbol qw(gensym);
830 \&    open(NULL, ">", File::Spec->devnull);
831 \&    my $pid = open3(gensym, \e*PH, ">&NULL", "cmd");
832 \&    while( <PH> ) { }
833 \&    waitpid($pid, 0);
836 To capture a program's \s-1STDERR\s0, but discard its \s-1STDOUT:\s0
838 .Vb 7
839 \&    use IPC::Open3;
840 \&    use File::Spec;
841 \&    use Symbol qw(gensym);
842 \&    open(NULL, ">", File::Spec->devnull);
843 \&    my $pid = open3(gensym, ">&NULL", \e*PH, "cmd");
844 \&    while( <PH> ) { }
845 \&    waitpid($pid, 0);
848 To capture a program's \s-1STDERR\s0, and let its \s-1STDOUT\s0 go to our own \s-1STDERR:\s0
850 .Vb 5
851 \&    use IPC::Open3;
852 \&    use Symbol qw(gensym);
853 \&    my $pid = open3(gensym, ">&STDERR", \e*PH, "cmd");
854 \&    while( <PH> ) { }
855 \&    waitpid($pid, 0);
858 To read both a command's \s-1STDOUT\s0 and its \s-1STDERR\s0 separately, you can
859 redirect them to temp files, let the command run, then read the temp
860 files:
862 .Vb 10
863 \&    use IPC::Open3;
864 \&    use Symbol qw(gensym);
865 \&    use IO::File;
866 \&    local *CATCHOUT = IO::File->new_tempfile;
867 \&    local *CATCHERR = IO::File->new_tempfile;
868 \&    my $pid = open3(gensym, ">&CATCHOUT", ">&CATCHERR", "cmd");
869 \&    waitpid($pid, 0);
870 \&    seek $_, 0, 0 for \e*CATCHOUT, \e*CATCHERR;
871 \&    while( <CATCHOUT> ) {}
872 \&    while( <CATCHERR> ) {}
875 But there's no real need for *both* to be tempfiles... the following
876 should work just as well, without deadlocking:
878 .Vb 9
879 \&    use IPC::Open3;
880 \&    use Symbol qw(gensym);
881 \&    use IO::File;
882 \&    local *CATCHERR = IO::File->new_tempfile;
883 \&    my $pid = open3(gensym, \e*CATCHOUT, ">&CATCHERR", "cmd");
884 \&    while( <CATCHOUT> ) {}
885 \&    waitpid($pid, 0);
886 \&    seek CATCHERR, 0, 0;
887 \&    while( <CATCHERR> ) {}
890 And it'll be faster, too, since we can begin processing the program's
891 stdout immediately, rather than waiting for the program to finish.
893 With any of these, you can change file descriptors before the call:
895 .Vb 2
896 \&    open(STDOUT, ">logfile");
897 \&    system("ls");
900 or you can use Bourne shell file-descriptor redirection:
902 .Vb 2
903 \&    $output = `$cmd 2>some_file`;
904 \&    open (PIPE, "cmd 2>some_file |");
907 You can also use file-descriptor redirection to make \s-1STDERR\s0 a
908 duplicate of \s-1STDOUT:\s0
910 .Vb 2
911 \&    $output = `$cmd 2>&1`;
912 \&    open (PIPE, "cmd 2>&1 |");
915 Note that you \fIcannot\fR simply open \s-1STDERR\s0 to be a dup of \s-1STDOUT\s0
916 in your Perl program and avoid calling the shell to do the redirection.
917 This doesn't work:
919 .Vb 2
920 \&    open(STDERR, ">&STDOUT");
921 \&    $alloutput = `cmd args`;  # stderr still escapes
924 This fails because the \fIopen()\fR makes \s-1STDERR\s0 go to where \s-1STDOUT\s0 was
925 going at the time of the \fIopen()\fR.  The backticks then make \s-1STDOUT\s0 go to
926 a string, but don't change \s-1STDERR\s0 (which still goes to the old
927 \&\s-1STDOUT\s0).
929 Note that you \fImust\fR use Bourne shell (\fIsh\fR\|(1)) redirection syntax in
930 backticks, not \fIcsh\fR\|(1)!  Details on why Perl's \fIsystem()\fR and backtick
931 and pipe opens all use the Bourne shell are in the
932 \&\fIversus/csh.whynot\fR article in the \*(L"Far More Than You Ever Wanted To
933 Know\*(R" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz .  To
934 capture a command's \s-1STDERR\s0 and \s-1STDOUT\s0 together:
936 .Vb 3
937 \&    $output = `cmd 2>&1`;                       # either with backticks
938 \&    $pid = open(PH, "cmd 2>&1 |");              # or with an open pipe
939 \&    while (<PH>) { }                            #    plus a read
942 To capture a command's \s-1STDOUT\s0 but discard its \s-1STDERR:\s0
944 .Vb 3
945 \&    $output = `cmd 2>/dev/null`;                # either with backticks
946 \&    $pid = open(PH, "cmd 2>/dev/null |");       # or with an open pipe
947 \&    while (<PH>) { }                            #    plus a read
950 To capture a command's \s-1STDERR\s0 but discard its \s-1STDOUT:\s0
952 .Vb 3
953 \&    $output = `cmd 2>&1 1>/dev/null`;           # either with backticks
954 \&    $pid = open(PH, "cmd 2>&1 1>/dev/null |");  # or with an open pipe
955 \&    while (<PH>) { }                            #    plus a read
958 To exchange a command's \s-1STDOUT\s0 and \s-1STDERR\s0 in order to capture the \s-1STDERR\s0
959 but leave its \s-1STDOUT\s0 to come out our old \s-1STDERR:\s0
961 .Vb 3
962 \&    $output = `cmd 3>&1 1>&2 2>&3 3>&-`;        # either with backticks
963 \&    $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
964 \&    while (<PH>) { }                            #    plus a read
967 To read both a command's \s-1STDOUT\s0 and its \s-1STDERR\s0 separately, it's easiest
968 and safest to redirect them separately to files, and then read from those
969 files when the program is done:
971 .Vb 1
972 \&    system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr");
975 Ordering is important in all these examples.  That's because the shell
976 processes file descriptor redirections in strictly left to right order.
978 .Vb 2
979 \&    system("prog args 1>tmpfile 2>&1");
980 \&    system("prog args 2>&1 1>tmpfile");
983 The first command sends both standard out and standard error to the
984 temporary file.  The second command sends only the old standard output
985 there, and the old standard error shows up on the old standard out.
986 .Sh "Why doesn't \fIopen()\fP return an error when a pipe open fails?"
987 .IX Subsection "Why doesn't open() return an error when a pipe open fails?"
988 If the second argument to a piped \fIopen()\fR contains shell
989 metacharacters, perl \fIfork()\fRs, then \fIexec()\fRs a shell to decode the
990 metacharacters and eventually run the desired program.  If the program
991 couldn't be run, it's the shell that gets the message, not Perl. All
992 your Perl program can find out is whether the shell itself could be
993 successfully started.  You can still capture the shell's \s-1STDERR\s0 and
994 check it for error messages.  See \*(L"How can I capture \s-1STDERR\s0 from an external command?\*(R" elsewhere in this document, or use the
995 IPC::Open3 module.
997 If there are no shell metacharacters in the argument of \fIopen()\fR, Perl
998 runs the command directly, without using the shell, and can correctly
999 report whether the command started.
1000 .Sh "What's wrong with using backticks in a void context?"
1001 .IX Subsection "What's wrong with using backticks in a void context?"
1002 Strictly speaking, nothing.  Stylistically speaking, it's not a good
1003 way to write maintainable code.  Perl has several operators for
1004 running external commands.  Backticks are one; they collect the output
1005 from the command for use in your program.  The \f(CW\*(C`system\*(C'\fR function is
1006 another; it doesn't do this.
1008 Writing backticks in your program sends a clear message to the readers
1009 of your code that you wanted to collect the output of the command.
1010 Why send a clear message that isn't true?
1012 Consider this line:
1014 .Vb 1
1015 \&    `cat /etc/termcap`;
1018 You forgot to check \f(CW$?\fR to see whether the program even ran
1019 correctly.  Even if you wrote
1021 .Vb 1
1022 \&    print `cat /etc/termcap`;
1025 this code could and probably should be written as
1027 .Vb 2
1028 \&    system("cat /etc/termcap") == 0
1029 \&        or die "cat program failed!";
1032 which will get the output quickly (as it is generated, instead of only
1033 at the end) and also check the return value.
1035 \&\fIsystem()\fR also provides direct control over whether shell wildcard
1036 processing may take place, whereas backticks do not.
1037 .Sh "How can I call backticks without shell processing?"
1038 .IX Subsection "How can I call backticks without shell processing?"
1039 This is a bit tricky.  You can't simply write the command
1040 like this:
1042 .Vb 1
1043 \&    @ok = `grep @opts '$search_string' @filenames`;
1046 As of Perl 5.8.0, you can use \fIopen()\fR with multiple arguments.
1047 Just like the list forms of \fIsystem()\fR and \fIexec()\fR, no shell
1048 escapes happen.
1050 .Vb 3
1051 \&   open( GREP, "-|", 'grep', @opts, $search_string, @filenames );
1052 \&   chomp(@ok = <GREP>);
1053 \&   close GREP;
1056 You can also:
1058 .Vb 10
1059 \&    my @ok = ();
1060 \&    if (open(GREP, "-|")) {
1061 \&        while (<GREP>) {
1062 \&            chomp;
1063 \&            push(@ok, $_);
1064 \&        }
1065 \&        close GREP;
1066 \&    } else {
1067 \&        exec 'grep', @opts, $search_string, @filenames;
1068 \&    }
1071 Just as with \fIsystem()\fR, no shell escapes happen when you \fIexec()\fR a list.
1072 Further examples of this can be found in \*(L"Safe Pipe Opens\*(R" in perlipc.
1074 Note that if you're use Microsoft, no solution to this vexing issue
1075 is even possible.  Even if Perl were to emulate \fIfork()\fR, you'd still
1076 be stuck, because Microsoft does not have a argc/argv\-style \s-1API\s0.
1077 .Sh "Why can't my script read from \s-1STDIN\s0 after I gave it \s-1EOF\s0 (^D on Unix, ^Z on \s-1MS\-DOS\s0)?"
1078 .IX Subsection "Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?"
1079 Some stdio's set error and eof flags that need clearing.  The
1080 \&\s-1POSIX\s0 module defines \fIclearerr()\fR that you can use.  That is the
1081 technically correct way to do it.  Here are some less reliable
1082 workarounds:
1083 .IP "1" 4
1084 .IX Item "1"
1085 Try keeping around the seekpointer and go there, like this:
1087 .Vb 2
1088 \&    $where = tell(LOG);
1089 \&    seek(LOG, $where, 0);
1091 .IP "2" 4
1092 .IX Item "2"
1093 If that doesn't work, try seeking to a different part of the file and
1094 then back.
1095 .IP "3" 4
1096 .IX Item "3"
1097 If that doesn't work, try seeking to a different part of
1098 the file, reading something, and then seeking back.
1099 .IP "4" 4
1100 .IX Item "4"
1101 If that doesn't work, give up on your stdio package and use sysread.
1102 .Sh "How can I convert my shell script to perl?"
1103 .IX Subsection "How can I convert my shell script to perl?"
1104 Learn Perl and rewrite it.  Seriously, there's no simple converter.
1105 Things that are awkward to do in the shell are easy to do in Perl, and
1106 this very awkwardness is what would make a shell\->perl converter
1107 nigh-on impossible to write.  By rewriting it, you'll think about what
1108 you're really trying to do, and hopefully will escape the shell's
1109 pipeline datastream paradigm, which while convenient for some matters,
1110 causes many inefficiencies.
1111 .Sh "Can I use perl to run a telnet or ftp session?"
1112 .IX Subsection "Can I use perl to run a telnet or ftp session?"
1113 Try the Net::FTP, TCP::Client, and Net::Telnet modules (available from
1114 \&\s-1CPAN\s0).  http://www.cpan.org/scripts/netstuff/telnet.emul.shar
1115 will also help for emulating the telnet protocol, but Net::Telnet is
1116 quite probably easier to use..
1118 If all you want to do is pretend to be telnet but don't need
1119 the initial telnet handshaking, then the standard dual-process
1120 approach will suffice:
1122 .Vb 12
1123 \&    use IO::Socket;             # new in 5.004
1124 \&    $handle = IO::Socket::INET->new('www.perl.com:80')
1125 \&            || die "can't connect to port 80 on www.perl.com: $!";
1126 \&    $handle->autoflush(1);
1127 \&    if (fork()) {               # XXX: undef means failure
1128 \&        select($handle);
1129 \&        print while <STDIN>;    # everything from stdin to socket
1130 \&    } else {
1131 \&        print while <$handle>;  # everything from socket to stdout
1132 \&    }
1133 \&    close $handle;
1134 \&    exit;
1136 .Sh "How can I write expect in Perl?"
1137 .IX Subsection "How can I write expect in Perl?"
1138 Once upon a time, there was a library called chat2.pl (part of the
1139 standard perl distribution), which never really got finished.  If you
1140 find it somewhere, \fIdon't use it\fR.  These days, your best bet is to
1141 look at the Expect module available from \s-1CPAN\s0, which also requires two
1142 other modules from \s-1CPAN\s0, IO::Pty and IO::Stty.
1143 .ie n .Sh "Is there a way to hide perl's command line from programs such as ""ps""?"
1144 .el .Sh "Is there a way to hide perl's command line from programs such as ``ps''?"
1145 .IX Subsection "Is there a way to hide perl's command line from programs such as ps?"
1146 First of all note that if you're doing this for security reasons (to
1147 avoid people seeing passwords, for example) then you should rewrite
1148 your program so that critical information is never given as an
1149 argument.  Hiding the arguments won't make your program completely
1150 secure.
1152 To actually alter the visible command line, you can assign to the
1153 variable \f(CW$0\fR as documented in perlvar.  This won't work on all
1154 operating systems, though.  Daemon programs like sendmail place their
1155 state there, as in:
1157 .Vb 1
1158 \&    $0 = "orcus [accepting connections]";
1160 .Sh "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?"
1161 .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?"
1162 .IP "Unix" 4
1163 .IX Item "Unix"
1164 In the strictest sense, it can't be done\*(--the script executes as a
1165 different process from the shell it was started from.  Changes to a
1166 process are not reflected in its parent\*(--only in any children
1167 created after the change.  There is shell magic that may allow you to
1168 fake it by \fIeval()\fRing the script's output in your shell; check out the
1169 comp.unix.questions \s-1FAQ\s0 for details.
1170 .Sh "How do I close a process's filehandle without waiting for it to complete?"
1171 .IX Subsection "How do I close a process's filehandle without waiting for it to complete?"
1172 Assuming your system supports such things, just send an appropriate signal
1173 to the process (see \*(L"kill\*(R" in perlfunc).  It's common to first send a \s-1TERM\s0
1174 signal, wait a little bit, and then send a \s-1KILL\s0 signal to finish it off.
1175 .Sh "How do I fork a daemon process?"
1176 .IX Subsection "How do I fork a daemon process?"
1177 If by daemon process you mean one that's detached (disassociated from
1178 its tty), then the following process is reported to work on most
1179 Unixish systems.  Non-Unix users should check their Your_OS::Process
1180 module for other solutions.
1181 .IP "\(bu" 4
1182 Open /dev/tty and use the \s-1TIOCNOTTY\s0 ioctl on it.  See tty
1183 for details.  Or better yet, you can just use the \fIPOSIX::setsid()\fR
1184 function, so you don't have to worry about process groups.
1185 .IP "\(bu" 4
1186 Change directory to /
1187 .IP "\(bu" 4
1188 Reopen \s-1STDIN\s0, \s-1STDOUT\s0, and \s-1STDERR\s0 so they're not connected to the old
1189 tty.
1190 .IP "\(bu" 4
1191 Background yourself like this:
1193 .Vb 1
1194 \&    fork && exit;
1197 The Proc::Daemon module, available from \s-1CPAN\s0, provides a function to
1198 perform these actions for you.
1199 .Sh "How do I find out if I'm running interactively or not?"
1200 .IX Subsection "How do I find out if I'm running interactively or not?"
1201 Good question.  Sometimes \f(CW\*(C`\-t STDIN\*(C'\fR and \f(CW\*(C`\-t STDOUT\*(C'\fR can give clues,
1202 sometimes not.
1204 .Vb 3
1205 \&    if (-t STDIN && -t STDOUT) {
1206 \&        print "Now what? ";
1207 \&    }
1210 On \s-1POSIX\s0 systems, you can test whether your own process group matches
1211 the current process group of your controlling terminal as follows:
1213 .Vb 9
1214 \&    use POSIX qw/getpgrp tcgetpgrp/;
1215 \&    open(TTY, "/dev/tty") or die $!;
1216 \&    $tpgrp = tcgetpgrp(fileno(*TTY));
1217 \&    $pgrp = getpgrp();
1218 \&    if ($tpgrp == $pgrp) {
1219 \&        print "foreground\en";
1220 \&    } else {
1221 \&        print "background\en";
1222 \&    }
1224 .Sh "How do I timeout a slow event?"
1225 .IX Subsection "How do I timeout a slow event?"
1226 Use the \fIalarm()\fR function, probably in conjunction with a signal
1227 handler, as documented in \*(L"Signals\*(R" in perlipc and the section on
1228 ``Signals'' in the Camel.  You may instead use the more flexible
1229 Sys::AlarmCall module available from \s-1CPAN\s0.
1231 The \fIalarm()\fR function is not implemented on all versions of Windows.
1232 Check the documentation for your specific version of Perl.
1233 .Sh "How do I set \s-1CPU\s0 limits?"
1234 .IX Subsection "How do I set CPU limits?"
1235 Use the BSD::Resource module from \s-1CPAN\s0.
1236 .Sh "How do I avoid zombies on a Unix system?"
1237 .IX Subsection "How do I avoid zombies on a Unix system?"
1238 Use the reaper code from \*(L"Signals\*(R" in perlipc to call \fIwait()\fR when a
1239 \&\s-1SIGCHLD\s0 is received, or else use the double-fork technique described
1240 in \*(L"How do I start a process in the background?\*(R" in perlfaq8.
1241 .Sh "How do I use an \s-1SQL\s0 database?"
1242 .IX Subsection "How do I use an SQL database?"
1243 The \s-1DBI\s0 module provides an abstract interface to most database
1244 servers and types, including Oracle, \s-1DB2\s0, Sybase, mysql, Postgresql,
1245 \&\s-1ODBC\s0, and flat files.  The \s-1DBI\s0 module accesses each database type
1246 through a database driver, or \s-1DBD\s0.  You can see a complete list of
1247 available drivers on \s-1CPAN:\s0 http://www.cpan.org/modules/by\-module/DBD/ .
1248 You can read more about \s-1DBI\s0 on http://dbi.perl.org .
1250 Other modules provide more specific access: Win32::ODBC, Alzabo, iodbc,
1251 and others found on \s-1CPAN\s0 Search: http://search.cpan.org .
1252 .Sh "How do I make a \fIsystem()\fP exit on control\-C?"
1253 .IX Subsection "How do I make a system() exit on control-C?"
1254 You can't.  You need to imitate the \fIsystem()\fR call (see perlipc for
1255 sample code) and then have a signal handler for the \s-1INT\s0 signal that
1256 passes the signal on to the subprocess.  Or you can check for it:
1258 .Vb 2
1259 \&    $rc = system($cmd);
1260 \&    if ($rc & 127) { die "signal death" }
1262 .Sh "How do I open a file without blocking?"
1263 .IX Subsection "How do I open a file without blocking?"
1264 If you're lucky enough to be using a system that supports
1265 non-blocking reads (most Unixish systems do), you need only to use the
1266 O_NDELAY or O_NONBLOCK flag from the Fcntl module in conjunction with
1267 \&\fIsysopen()\fR:
1269 .Vb 3
1270 \&    use Fcntl;
1271 \&    sysopen(FH, "/tmp/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)
1272 \&        or die "can't open /tmp/somefile: $!":
1274 .Sh "How do I install a module from \s-1CPAN\s0?"
1275 .IX Subsection "How do I install a module from CPAN?"
1276 The easiest way is to have a module also named \s-1CPAN\s0 do it for you.
1277 This module comes with perl version 5.004 and later.
1279 .Vb 1
1280 \&    $ perl -MCPAN -e shell
1283 .Vb 2
1284 \&    cpan shell -- CPAN exploration and modules installation (v1.59_54)
1285 \&    ReadLine support enabled
1288 .Vb 1
1289 \&    cpan> install Some::Module
1292 To manually install the \s-1CPAN\s0 module, or any well-behaved \s-1CPAN\s0 module
1293 for that matter, follow these steps:
1294 .IP "1" 4
1295 .IX Item "1"
1296 Unpack the source into a temporary area.
1297 .IP "2" 4
1298 .IX Item "2"
1299 .Vb 1
1300 \&    perl Makefile.PL
1302 .IP "3" 4
1303 .IX Item "3"
1304 .Vb 1
1305 \&    make
1307 .IP "4" 4
1308 .IX Item "4"
1309 .Vb 1
1310 \&    make test
1312 .IP "5" 4
1313 .IX Item "5"
1314 .Vb 1
1315 \&    make install
1318 If your version of perl is compiled without dynamic loading, then you
1319 just need to replace step 3 (\fBmake\fR) with \fBmake perl\fR and you will
1320 get a new \fIperl\fR binary with your extension linked in.
1322 See ExtUtils::MakeMaker for more details on building extensions.
1323 See also the next question, ``What's the difference between require
1324 and use?''.
1325 .Sh "What's the difference between require and use?"
1326 .IX Subsection "What's the difference between require and use?"
1327 Perl offers several different ways to include code from one file into
1328 another.  Here are the deltas between the various inclusion constructs:
1330 .Vb 3
1331 \&    1)  do $file is like eval `cat $file`, except the former
1332 \&        1.1: searches @INC and updates %INC.
1333 \&        1.2: bequeaths an *unrelated* lexical scope on the eval'ed code.
1336 .Vb 3
1337 \&    2)  require $file is like do $file, except the former
1338 \&        2.1: checks for redundant loading, skipping already loaded files.
1339 \&        2.2: raises an exception on failure to find, compile, or execute $file.
1342 .Vb 3
1343 \&    3)  require Module is like require "Module.pm", except the former
1344 \&        3.1: translates each "::" into your system's directory separator.
1345 \&        3.2: primes the parser to disambiguate class Module as an indirect object.
1348 .Vb 3
1349 \&    4)  use Module is like require Module, except the former
1350 \&        4.1: loads the module at compile time, not run-time.
1351 \&        4.2: imports symbols and semantics from that package to the current one.
1354 In general, you usually want \f(CW\*(C`use\*(C'\fR and a proper Perl module.
1355 .Sh "How do I keep my own module/library directory?"
1356 .IX Subsection "How do I keep my own module/library directory?"
1357 When you build modules, use the \s-1PREFIX\s0 and \s-1LIB\s0 options when generating
1358 Makefiles:
1360 .Vb 1
1361 \&    perl Makefile.PL PREFIX=/mydir/perl LIB=/mydir/perl/lib
1364 then either set the \s-1PERL5LIB\s0 environment variable before you run
1365 scripts that use the modules/libraries (see perlrun) or say
1367 .Vb 1
1368 \&    use lib '/mydir/perl/lib';
1371 This is almost the same as
1373 .Vb 3
1374 \&    BEGIN {
1375 \&        unshift(@INC, '/mydir/perl/lib');
1376 \&    }
1379 except that the lib module checks for machine-dependent subdirectories.
1380 See Perl's lib for more information.
1381 .Sh "How do I add the directory my program lives in to the module/library search path?"
1382 .IX Subsection "How do I add the directory my program lives in to the module/library search path?"
1383 .Vb 3
1384 \&    use FindBin;
1385 \&    use lib "$FindBin::Bin";
1386 \&    use your_own_modules;
1388 .Sh "How do I add a directory to my include path (@INC) at runtime?"
1389 .IX Subsection "How do I add a directory to my include path (@INC) at runtime?"
1390 Here are the suggested ways of modifying your include path:
1392 .Vb 5
1393 \&    the PERLLIB environment variable
1394 \&    the PERL5LIB environment variable
1395 \&    the perl -Idir command line flag
1396 \&    the use lib pragma, as in
1397 \&        use lib "$ENV{HOME}/myown_perllib";
1400 The latter is particularly useful because it knows about machine
1401 dependent architectures.  The lib.pm pragmatic module was first
1402 included with the 5.002 release of Perl.
1403 .Sh "What is socket.ph and where do I get it?"
1404 .IX Subsection "What is socket.ph and where do I get it?"
1405 It's a perl4\-style file defining values for system networking
1406 constants.  Sometimes it is built using h2ph when Perl is installed,
1407 but other times it is not.  Modern programs \f(CW\*(C`use Socket;\*(C'\fR instead.
1408 .SH "AUTHOR AND COPYRIGHT"
1409 .IX Header "AUTHOR AND COPYRIGHT"
1410 Copyright (c) 1997\-2003 Tom Christiansen and Nathan Torkington.
1411 All rights reserved.
1413 This documentation is free; you can redistribute it and/or modify it
1414 under the same terms as Perl itself.
1416 Irrespective of its distribution, all code examples in this file
1417 are hereby placed into the public domain.  You are permitted and
1418 encouraged to use this code in your own programs for fun
1419 or for profit as you see fit.  A simple comment in the code giving
1420 credit would be courteous but is not required.