Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / man / man1 / perlfaq8.1
CommitLineData
86530b38
AT
1.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
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
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
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"
58..
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'
101.\}
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 \
117\{\
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
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "PERLFAQ8 1"
132.TH PERLFAQ8 1 "2002-06-08" "perl v5.8.0" "Perl Programmers Reference Guide"
133.SH "NAME"
134perlfaq8 \- System Interaction ($Revision: 1.8 $, $Date: 2002/05/16 12:41:42 $)
135.SH "DESCRIPTION"
136.IX Header "DESCRIPTION"
137This section of the Perl \s-1FAQ\s0 covers questions involving operating
138system interaction. Topics include interprocess communication (\s-1IPC\s0),
139control over the user-interface (keyboard, screen and pointing
140devices), and most anything else not related to data manipulation.
141.PP
142Read the FAQs and documentation specific to the port of perl to your
143operating system (eg, perlvms, perlplan9, ...). These should
144contain 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?"
147The $^O variable ($OSNAME if you use English) contains an indication of
148the name of the operating system (not its release number) that your perl
149binary was built for.
150.Sh "How come \fIexec()\fP doesn't return?"
151.IX Subsection "How come exec() doesn't return?"
152Because that's what it does: it replaces your currently running
153program with a different one. If you want to keep going (as is
154probably the case if you're asking this question) use \fIsystem()\fR
155instead.
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?"
158How 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
168.Ve
169.IP "Screen" 4
170.IX Item "Screen"
171.Vb 3
172\& Term::Cap Standard perl distribution
173\& Curses CPAN
174\& Term::ANSIColor CPAN
175.Ve
176.IP "Mouse" 4
177.IX Item "Mouse"
178.Vb 1
179\& Tk CPAN
180.Ve
181.PP
182Some 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?"
185In general, you don't, because you don't know whether
186the recipient has a color-aware display device. If you
187know that they have an \s-1ANSI\s0 terminal that understands
188color, you can use the Term::ANSIColor module from \s-1CPAN:\s0
189.PP
190.Vb 3
191\& use Term::ANSIColor;
192\& print color("red"), "Stop!\en", color("reset");
193\& print color("green"), "Go!\en", color("reset");
194.Ve
195.PP
196Or like this:
197.PP
198.Vb 3
199\& use Term::ANSIColor qw(:constants);
200\& print RED, "Stop!\en", RESET;
201\& print GREEN, "Go!\en", RESET;
202.Ve
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?"
205Controlling input buffering is a remarkably system-dependent matter.
206On 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
208portability snags.
209.PP
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";
217.Ve
218.PP
219The Term::ReadKey module from \s-1CPAN\s0 offers an easy-to-use interface that
220should be more efficient than shelling out to \fBstty\fR for each key.
221It even includes limited support for Windows.
222.PP
223.Vb 4
224\& use Term::ReadKey;
225\& ReadMode('cbreak');
226\& $key = ReadKey(0);
227\& ReadMode('normal');
228.Ve
229.PP
230However, using the code requires that you have a working C compiler
231and can use it to build and install a \s-1CPAN\s0 module. Here's a solution
232using the standard \s-1POSIX\s0 module, which is already on your systems
233(assuming your system supports \s-1POSIX\s0).
234.PP
235.Vb 2
236\& use HotKey;
237\& $key = readkey();
238.Ve
239.PP
240And here's the HotKey module, which hides the somewhat mystifying calls
241to manipulate the \s-1POSIX\s0 termios structures.
242.PP
243.Vb 2
244\& # HotKey.pm
245\& package HotKey;
246.Ve
247.PP
248.Vb 2
249\& @ISA = qw(Exporter);
250\& @EXPORT = qw(cbreak cooked readkey);
251.Ve
252.PP
253.Vb 3
254\& use strict;
255\& use POSIX qw(:termios_h);
256\& my ($term, $oterm, $echo, $noecho, $fd_stdin);
257.Ve
258.PP
259.Vb 4
260\& $fd_stdin = fileno(STDIN);
261\& $term = POSIX::Termios->new();
262\& $term->getattr($fd_stdin);
263\& $oterm = $term->getlflag();
264.Ve
265.PP
266.Vb 2
267\& $echo = ECHO | ECHOK | ICANON;
268\& $noecho = $oterm & ~$echo;
269.Ve
270.PP
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\& }
277.Ve
278.PP
279.Vb 5
280\& sub cooked {
281\& $term->setlflag($oterm);
282\& $term->setcc(VTIME, 0);
283\& $term->setattr($fd_stdin, TCSANOW);
284\& }
285.Ve
286.PP
287.Vb 7
288\& sub readkey {
289\& my $key = '';
290\& cbreak();
291\& sysread(STDIN, $key, 1);
292\& cooked();
293\& return $key;
294\& }
295.Ve
296.PP
297.Vb 1
298\& END { cooked() }
299.Ve
300.PP
301.Vb 1
302\& 1;
303.Ve
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?"
306The easiest way to do this is to read a key in nonblocking mode with the
307Term::ReadKey module from \s-1CPAN\s0, passing it an argument of \-1 to indicate
308not to block:
309.PP
310.Vb 1
311\& use Term::ReadKey;
312.Ve
313.PP
314.Vb 1
315\& ReadMode('cbreak');
316.Ve
317.PP
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\& }
324.Ve
325.PP
326.Vb 1
327\& ReadMode('normal'); # restore normal tty settings
328.Ve
329.Sh "How do I clear the screen?"
330.IX Subsection "How do I clear the screen?"
331If you only have do so infrequently, use \f(CW\*(C`system\*(C'\fR:
332.PP
333.Vb 1
334\& system("clear");
335.Ve
336.PP
337If you have to do this a lot, save the clear string
338so you can print it 100 times without calling a program
339100 times:
340.PP
341.Vb 2
342\& $clear_string = `clear`;
343\& print $clear_string;
344.Ve
345.PP
346If you're planning on doing other screen manipulations, like cursor
347positions, etc, you might wish to use Term::Cap module:
348.PP
349.Vb 3
350\& use Term::Cap;
351\& $terminal = Term::Cap->Tgetent( {OSPEED => 9600} );
352\& $clear_string = $terminal->Tputs('cl');
353.Ve
354.Sh "How do I get the screen size?"
355.IX Subsection "How do I get the screen size?"
356If you have Term::ReadKey module installed from \s-1CPAN\s0,
357you can use it to fetch the width and height in characters
358and in pixels:
359.PP
360.Vb 2
361\& use Term::ReadKey;
362\& ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
363.Ve
364.PP
365This is more portable than the raw \f(CW\*(C`ioctl\*(C'\fR, but not as
366illustrative:
367.PP
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";
379.Ve
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.)
384.PP
385There's an example of this in \*(L"crypt\*(R" in perlfunc). First, you put the
386terminal into \*(L"no echo\*(R" mode, then just read the password normally.
387You may do this with an old-style \fIioctl()\fR function, \s-1POSIX\s0 terminal
388control (see \s-1POSIX\s0 or its documentation the Camel Book), or a call
389to the \fBstty\fR program, with varying degrees of portability.
390.PP
391You can also do this for most systems using the Term::ReadKey module
392from \s-1CPAN\s0, which is easier to use and in theory more portable.
393.PP
394.Vb 1
395\& use Term::ReadKey;
396.Ve
397.PP
398.Vb 2
399\& ReadMode('noecho');
400\& $password = ReadLine(0);
401.Ve
402.Sh "How do I read and write the serial port?"
403.IX Subsection "How do I read and write the serial port?"
404This depends on which operating system your program is running on. In
405the case of Unix, the serial ports will be accessible through files in
406/dev; on other systems, device names will doubtless differ.
407Several problem areas common to all device interaction are the
408following:
409.IP "lockfiles" 4
410.IX Item "lockfiles"
411Your system may use lockfiles to control multiple access. Make sure
412you follow the correct protocol. Unpredictable behavior can result
413from multiple processes reading from one device.
414.IP "open mode" 4
415.IX Item "open mode"
416If you expect to use both read and write operations on the device,
417you'll have to open it for update (see \*(L"open\*(R" in perlfunc for
418details). You may wish to open it without running the risk of
419blocking by using \fIsysopen()\fR and \f(CW\*(C`O_RDWR|O_NDELAY|O_NOCTTY\*(C'\fR from the
420Fcntl 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"
424Some devices will be expecting a \*(L"\er\*(R" at the end of each line rather
425than a \*(L"\en\*(R". In some ports of perl, \*(L"\er\*(R" and \*(L"\en\*(R" are different from
426their usual (Unix) \s-1ASCII\s0 values of \*(L"\e012\*(R" and \*(L"\e015\*(R". You may have to
427give 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").
429.Sp
430.Vb 2
431\& print DEV "atv1\e012"; # wrong, for some devices
432\& print DEV "atv1\e015"; # right, for some devices
433.Ve
434.Sp
435Even though with normal text files a \*(L"\en\*(R" will do the trick, there is
436still no unified scheme for terminating a line that is portable
437between Unix, DOS/Win, and Macintosh, except to terminate \fI\s-1ALL\s0\fR line
438ends with \*(L"\e015\e012\*(R", and strip what you don't need from the output.
439This applies especially to socket I/O and autoflushing, discussed
440next.
441.IP "flushing output" 4
442.IX Item "flushing output"
443If you expect characters to get to your device when you \fIprint()\fR them,
444you'll want to autoflush that filehandle. You can use \fIselect()\fR
445and the \f(CW$|\fR variable to control autoflushing (see perlvar/$
446and \*(L"select\*(R" in perlfunc, or perlfaq5, ``How do I flush/unbuffer an
447output filehandle? Why must I do this?''):
448.Sp
449.Vb 3
450\& $oldh = select(DEV);
451\& $| = 1;
452\& select($oldh);
453.Ve
454.Sp
455You'll also see code that does this without a temporary variable, as in
456.Sp
457.Vb 1
458\& select((select(DEV), $| = 1)[0]);
459.Ve
460.Sp
461Or if you don't mind pulling in a few thousand lines
462of code just because you're afraid of a little $| variable:
463.Sp
464.Vb 2
465\& use IO::Handle;
466\& DEV->autoflush(1);
467.Ve
468.Sp
469As mentioned in the previous item, this still doesn't work when using
470socket I/O between Unix and Macintosh. You'll need to hard code your
471line terminators, in that case.
472.IP "non-blocking input" 4
473.IX Item "non-blocking input"
474If you are doing a blocking \fIread()\fR or \fIsysread()\fR, you'll have to
475arrange 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
477have 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.
480.PP
481While 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,
483sysopen, \s-1POSIX\s0's tcgetattr business, and various other functions that
484go bump in the night, finally came up with this:
485.PP
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\& }
500.Ve
501.Sh "How do I decode encrypted password files?"
502.IX Subsection "How do I decode encrypted password files?"
503You spend lots and lots of money on dedicated hardware, but this is
504bound to get you talked about.
505.PP
506Seriously, you can't if they are Unix password files\*(--the Unix
507password system employs one-way encryption. It's more like hashing than
508encryption. The best you can check is whether something else hashes to
509the same string. You can't turn a hash back into the original string.
510Programs like Crack
511can forcibly (and intelligently) try to guess passwords, but don't
512(can't) guarantee quick success.
513.PP
514If you're worried about users selecting bad passwords, you should
515proactively 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?"
519You could use
520.PP
521.Vb 1
522\& system("cmd &")
523.Ve
524.PP
525or you could use fork as documented in \*(L"fork\*(R" in perlfunc, with
526further examples in perlipc. Some things to be aware of, if you're
527on a Unix-like system:
528.IP "\s-1STDIN\s0, \s-1STDOUT\s0, and \s-1STDERR\s0 are shared" 4
529.IX Item "STDIN, STDOUT, and STDERR are shared"
530Both the main process and the backgrounded one (the \*(L"child\*(R" process)
531share the same \s-1STDIN\s0, \s-1STDOUT\s0 and \s-1STDERR\s0 filehandles. If both try to
532access them at once, strange things can happen. You may want to close
533or reopen these for the child. You can get around this with
534\&\f(CW\*(C`open\*(C'\fRing a pipe (see \*(L"open\*(R" in perlfunc) but on some systems this
535means that the child process cannot outlive the parent.
536.IP "Signals" 4
537.IX Item "Signals"
538You'll have to catch the \s-1SIGCHLD\s0 signal, and possibly \s-1SIGPIPE\s0 too.
539\&\s-1SIGCHLD\s0 is sent when the backgrounded process finishes. \s-1SIGPIPE\s0 is
540sent when you write to a filehandle whose child process has closed (an
541untrapped \s-1SIGPIPE\s0 can cause your program to silently die). This is
542not an issue with \f(CW\*(C`system("cmd&")\*(C'\fR.
543.IP "Zombies" 4
544.IX Item "Zombies"
545You have to be prepared to \*(L"reap\*(R" the child process when it finishes
546.Sp
547.Vb 1
548\& $SIG{CHLD} = sub { wait };
549.Ve
550.Sp
551See \*(L"Signals\*(R" in perlipc for other examples of code to do this.
552Zombies are not an issue with \f(CW\*(C`system("prog &")\*(C'\fR.
553.Sh "How do I trap control characters/signals?"
554.IX Subsection "How do I trap control characters/signals?"
555You don't actually \*(L"trap\*(R" a control character. Instead, that character
556generates a signal which is sent to your terminal's currently
557foregrounded process group, which you then trap in your process.
558Signals are documented in \*(L"Signals\*(R" in perlipc and the
559section on ``Signals'' in the Camel.
560.PP
561Be warned that very few C libraries are re\-entrant. Therefore, if you
562attempt to \fIprint()\fR in a handler that got invoked during another stdio
563operation your internal structures will likely be in an
564inconsistent state, and your program will dump core. You can
565sometimes avoid this by using \fIsyswrite()\fR instead of \fIprint()\fR.
566.PP
567Unless you're exceedingly careful, the only safe things to do inside a
568signal handler are (1) set a variable and (2) exit. In the first case,
569you should only set a variable in such a way that \fImalloc()\fR is not
570called (eg, by setting a variable that already has a value).
571.PP
572For example:
573.PP
574.Vb 5
575\& $Interrupted = 0; # to ensure it has a value
576\& $SIG{INT} = sub {
577\& $Interrupted++;
578\& syswrite(STDERR, "ouch\en", 5);
579\& }
580.Ve
581.PP
582However, because syscalls restart by default, you'll find that if
583you're in a \*(L"slow\*(R" call, such as <\s-1FH\s0>, \fIread()\fR, \fIconnect()\fR, or
584\&\fIwait()\fR, that the only way to terminate them is by \*(L"longjumping\*(R" out;
585that is, by raising an exception. See the time-out handler for a
586blocking \fIflock()\fR in \*(L"Signals\*(R" in perlipc or the section on ``Signals''
587in the Camel book.
588.Sh "How do I modify the shadow password file on a Unix system?"
589.IX Subsection "How do I modify the shadow password file on a Unix system?"
590If perl was installed correctly and your shadow library was written
591properly, the getpw*() functions described in perlfunc should in
592theory provide (read\-only) access to entries in the shadow password
593file. To change the file, make a new shadow password file (the format
594varies from system to system\*(--see \fIpasswd\fR\|(5) for specifics) and use
595\&\fIpwd_mkdb\fR\|(8) to install it (see \fIpwd_mkdb\fR\|(8) for more details).
596.Sh "How do I set the time and date?"
597.IX Subsection "How do I set the time and date?"
598Assuming you're running under sufficient permissions, you should be
599able to set the system-wide date and time by running the \fIdate\fR\|(1)
600program. (There is no way to set the time and date on a per-process
601basis.) This mechanism will work for Unix, \s-1MS\-DOS\s0, Windows, and \s-1NT\s0;
602the \s-1VMS\s0 equivalent is \f(CW\*(C`set time\*(C'\fR.
603.PP
604However, if all you want to do is change your time zone, you can
605probably get away with setting an environment variable:
606.PP
607.Vb 3
608\& $ENV{TZ} = "MST7MDT"; # unixish
609\& $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
610\& system "trn comp.lang.perl.misc";
611.Ve
612.Sh "How can I \fIsleep()\fP or \fIalarm()\fP for under a second?"
613.IX Subsection "How can I sleep() or alarm() for under a second?"
614If you want finer granularity than the 1 second that the \fIsleep()\fR
615function provides, the easiest way is to use the \fIselect()\fR function as
616documented in \*(L"select\*(R" in perlfunc. Try the Time::HiRes and
617the BSD::Itimer modules (available from \s-1CPAN\s0, and starting from
618Perl 5.8 Time::HiRes is part of the standard distribution).
619.Sh "How can I measure time under a second?"
620.IX Subsection "How can I measure time under a second?"
621In general, you may not be able to. The Time::HiRes module (available
622from \s-1CPAN\s0, and starting from Perl 5.8 part of the standard distribution)
623provides this functionality for some systems.
624.PP
625If your system supports both the \fIsyscall()\fR function in Perl as well as
626a system call like \fIgettimeofday\fR\|(2), then you may be able to do
627something like this:
628.PP
629.Vb 1
630\& require 'sys/syscall.ph';
631.Ve
632.PP
633.Vb 1
634\& $TIMEVAL_T = "LL";
635.Ve
636.PP
637.Vb 1
638\& $done = $start = pack($TIMEVAL_T, ());
639.Ve
640.PP
641.Vb 2
642\& syscall(&SYS_gettimeofday, $start, 0) != -1
643\& or die "gettimeofday: $!";
644.Ve
645.PP
646.Vb 3
647\& ##########################
648\& # DO YOUR OPERATION HERE #
649\& ##########################
650.Ve
651.PP
652.Vb 2
653\& syscall( &SYS_gettimeofday, $done, 0) != -1
654\& or die "gettimeofday: $!";
655.Ve
656.PP
657.Vb 2
658\& @start = unpack($TIMEVAL_T, $start);
659\& @done = unpack($TIMEVAL_T, $done);
660.Ve
661.PP
662.Vb 2
663\& # fix microseconds
664\& for ($done[1], $start[1]) { $_ /= 1_000_000 }
665.Ve
666.PP
667.Vb 3
668\& $delta_time = sprintf "%.4f", ($done[0] + $done[1] )
669\& -
670\& ($start[0] + $start[1] );
671.Ve
672.Sh "How can I do an \fIatexit()\fP or \fIsetjmp()\fP/\fIlongjmp()\fP? (Exception handling)"
673.IX Subsection "How can I do an atexit() or setjmp()/longjmp()? (Exception handling)"
674Release 5 of Perl added the \s-1END\s0 block, which can be used to simulate
675\&\fIatexit()\fR. Each package's \s-1END\s0 block is called when the program or
676thread ends (see perlmod manpage for more details).
677.PP
678For example, you can use this to make sure your filter program
679managed to finish its output without filling up the disk:
680.PP
681.Vb 3
682\& END {
683\& close(STDOUT) || die "stdout close failed: $!";
684\& }
685.Ve
686.PP
687The \s-1END\s0 block isn't called when untrapped signals kill the program,
688though, so if you use \s-1END\s0 blocks you should also use
689.PP
690.Vb 1
691\& use sigtrap qw(die normal-signals);
692.Ve
693.PP
694Perl's exception-handling mechanism is its \fIeval()\fR operator. You can
695use \fIeval()\fR as setjmp and \fIdie()\fR as longjmp. For details of this, see
696the section on signals, especially the time-out handler for a blocking
697\&\fIflock()\fR in \*(L"Signals\*(R" in perlipc or the section on ``Signals'' in
698the Camel Book.
699.PP
700If exception handling is all you're interested in, try the
701exceptions.pl library (part of the standard perl distribution).
702.PP
703If you want the \fIatexit()\fR syntax (and an \fIrmexit()\fR as well), try the
704AtExit module available from \s-1CPAN\s0.
705.ie n .Sh "Why doesn't my sockets program work under System V (Solaris)? What does the error message ""Protocol not supported"" mean?"
706.el .Sh "Why doesn't my sockets program work under System V (Solaris)? What does the error message ``Protocol not supported'' mean?"
707.IX Subsection "Why doesn't my sockets program work under System V (Solaris)? What does the error message Protocol not supported mean?"
708Some Sys-V based systems, notably Solaris 2.X, redefined some of the
709standard socket constants. Since these were constant across all
710architectures, they were often hardwired into perl code. The proper
711way to deal with this is to \*(L"use Socket\*(R" to get the correct values.
712.PP
713Note that even though SunOS and Solaris are binary compatible, these
714values are different. Go figure.
715.Sh "How can I call my system's unique C functions from Perl?"
716.IX Subsection "How can I call my system's unique C functions from Perl?"
717In most cases, you write an external module to do it\*(--see the answer
718to \*(L"Where can I learn about linking C with Perl? [h2xs, xsubpp]\*(R".
719However, if the function is a system call, and your system supports
720\&\fIsyscall()\fR, you can use the syscall function (documented in
721perlfunc).
722.PP
723Remember to check the modules that came with your distribution, and
724\&\s-1CPAN\s0 as well\*(--someone may already have written a module to do it.
725.Sh "Where do I get the include files to do \fIioctl()\fP or \fIsyscall()\fP?"
726.IX Subsection "Where do I get the include files to do ioctl() or syscall()?"
727Historically, these would be generated by the h2ph tool, part of the
728standard perl distribution. This program converts \fIcpp\fR\|(1) directives
729in C header files to files containing subroutine definitions, like
730&SYS_getitimer, which you can use as arguments to your functions.
731It doesn't work perfectly, but it usually gets most of the job done.
732Simple files like \fIerrno.h\fR, \fIsyscall.h\fR, and \fIsocket.h\fR were fine,
733but the hard ones like \fIioctl.h\fR nearly always need to hand\-edited.
734Here's how to install the *.ph files:
735.PP
736.Vb 3
737\& 1. become super-user
738\& 2. cd /usr/include
739\& 3. h2ph *.h */*.h
740.Ve
741.PP
742If your system supports dynamic loading, for reasons of portability and
743sanity you probably ought to use h2xs (also part of the standard perl
744distribution). This tool converts C header files to Perl extensions.
745See perlxstut for how to get started with h2xs.
746.PP
747If your system doesn't support dynamic loading, you still probably
748ought to use h2xs. See perlxstut and ExtUtils::MakeMaker for
749more information (in brief, just use \fBmake perl\fR instead of a plain
750\&\fBmake\fR to rebuild perl with a new static extension).
751.Sh "Why do setuid perl scripts complain about kernel problems?"
752.IX Subsection "Why do setuid perl scripts complain about kernel problems?"
753Some operating systems have bugs in the kernel that make setuid
754scripts inherently insecure. Perl gives you a number of options
755(described in perlsec) to work around such systems.
756.Sh "How can I open a pipe both to and from a command?"
757.IX Subsection "How can I open a pipe both to and from a command?"
758The IPC::Open2 module (part of the standard perl distribution) is an
759easy-to-use approach that internally uses \fIpipe()\fR, \fIfork()\fR, and \fIexec()\fR to do
760the job. Make sure you read the deadlock warnings in its documentation,
761though (see IPC::Open2). See
762\&\*(L"Bidirectional Communication with Another Process\*(R" in perlipc and
763\&\*(L"Bidirectional Communication with Yourself\*(R" in perlipc
764.PP
765You may also use the IPC::Open3 module (part of the standard perl
766distribution), but be warned that it has a different order of
767arguments from IPC::Open2 (see IPC::Open3).
768.Sh "Why can't I get the output of a command with \fIsystem()\fP?"
769.IX Subsection "Why can't I get the output of a command with system()?"
770You're confusing the purpose of \fIsystem()\fR and backticks (``). \fIsystem()\fR
771runs a command and returns exit status information (as a 16 bit value:
772the low 7 bits are the signal the process died from, if any, and
773the high 8 bits are the actual exit value). Backticks (``) run a
774command and return what it sent to \s-1STDOUT\s0.
775.PP
776.Vb 2
777\& $exit_status = system("mail-users");
778\& $output_string = `ls`;
779.Ve
780.Sh "How can I capture \s-1STDERR\s0 from an external command?"
781.IX Subsection "How can I capture STDERR from an external command?"
782There are three basic ways of running external commands:
783.PP
784.Vb 3
785\& system $cmd; # using system()
786\& $output = `$cmd`; # using backticks (``)
787\& open (PIPE, "cmd |"); # using open()
788.Ve
789.PP
790With \fIsystem()\fR, both \s-1STDOUT\s0 and \s-1STDERR\s0 will go the same place as the
791script's \s-1STDOUT\s0 and \s-1STDERR\s0, unless the \fIsystem()\fR command redirects them.
792Backticks and \fIopen()\fR read \fBonly\fR the \s-1STDOUT\s0 of your command.
793.PP
794With any of these, you can change file descriptors before the call:
795.PP
796.Vb 2
797\& open(STDOUT, ">logfile");
798\& system("ls");
799.Ve
800.PP
801or you can use Bourne shell file-descriptor redirection:
802.PP
803.Vb 2
804\& $output = `$cmd 2>some_file`;
805\& open (PIPE, "cmd 2>some_file |");
806.Ve
807.PP
808You can also use file-descriptor redirection to make \s-1STDERR\s0 a
809duplicate of \s-1STDOUT:\s0
810.PP
811.Vb 2
812\& $output = `$cmd 2>&1`;
813\& open (PIPE, "cmd 2>&1 |");
814.Ve
815.PP
816Note that you \fIcannot\fR simply open \s-1STDERR\s0 to be a dup of \s-1STDOUT\s0
817in your Perl program and avoid calling the shell to do the redirection.
818This doesn't work:
819.PP
820.Vb 2
821\& open(STDERR, ">&STDOUT");
822\& $alloutput = `cmd args`; # stderr still escapes
823.Ve
824.PP
825This fails because the \fIopen()\fR makes \s-1STDERR\s0 go to where \s-1STDOUT\s0 was
826going at the time of the \fIopen()\fR. The backticks then make \s-1STDOUT\s0 go to
827a string, but don't change \s-1STDERR\s0 (which still goes to the old
828\&\s-1STDOUT\s0).
829.PP
830Note that you \fImust\fR use Bourne shell (\fIsh\fR\|(1)) redirection syntax in
831backticks, not \fIcsh\fR\|(1)! Details on why Perl's \fIsystem()\fR and backtick
832and pipe opens all use the Bourne shell are in the
833\&\fIversus/csh.whynot\fR article in the \*(L"Far More Than You Ever Wanted To
834Know\*(R" collection in http://www.cpan.org/olddoc/FMTEYEWTK.tgz . To
835capture a command's \s-1STDERR\s0 and \s-1STDOUT\s0 together:
836.PP
837.Vb 3
838\& $output = `cmd 2>&1`; # either with backticks
839\& $pid = open(PH, "cmd 2>&1 |"); # or with an open pipe
840\& while (<PH>) { } # plus a read
841.Ve
842.PP
843To capture a command's \s-1STDOUT\s0 but discard its \s-1STDERR:\s0
844.PP
845.Vb 3
846\& $output = `cmd 2>/dev/null`; # either with backticks
847\& $pid = open(PH, "cmd 2>/dev/null |"); # or with an open pipe
848\& while (<PH>) { } # plus a read
849.Ve
850.PP
851To capture a command's \s-1STDERR\s0 but discard its \s-1STDOUT:\s0
852.PP
853.Vb 3
854\& $output = `cmd 2>&1 1>/dev/null`; # either with backticks
855\& $pid = open(PH, "cmd 2>&1 1>/dev/null |"); # or with an open pipe
856\& while (<PH>) { } # plus a read
857.Ve
858.PP
859To exchange a command's \s-1STDOUT\s0 and \s-1STDERR\s0 in order to capture the \s-1STDERR\s0
860but leave its \s-1STDOUT\s0 to come out our old \s-1STDERR:\s0
861.PP
862.Vb 3
863\& $output = `cmd 3>&1 1>&2 2>&3 3>&-`; # either with backticks
864\& $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
865\& while (<PH>) { } # plus a read
866.Ve
867.PP
868To read both a command's \s-1STDOUT\s0 and its \s-1STDERR\s0 separately, it's easiest
869and safest to redirect them separately to files, and then read from those
870files when the program is done:
871.PP
872.Vb 1
873\& system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr");
874.Ve
875.PP
876Ordering is important in all these examples. That's because the shell
877processes file descriptor redirections in strictly left to right order.
878.PP
879.Vb 2
880\& system("prog args 1>tmpfile 2>&1");
881\& system("prog args 2>&1 1>tmpfile");
882.Ve
883.PP
884The first command sends both standard out and standard error to the
885temporary file. The second command sends only the old standard output
886there, and the old standard error shows up on the old standard out.
887.Sh "Why doesn't \fIopen()\fP return an error when a pipe open fails?"
888.IX Subsection "Why doesn't open() return an error when a pipe open fails?"
889If the second argument to a piped \f(CW\*(C`open\*(C'\fR contains shell
890metacharacters, perl \fIfork()\fRs, then \fIexec()\fRs a shell to decode the
891metacharacters and eventually run the desired program. If the program
892couldn't be run, it's the shell that gets the message, not Perl. All
893your Perl program can find out is whether the shell itself could be
894successfully started. You can still capture the shell's \s-1STDERR\s0 and
895check 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
896IPC::Open3 module.
897.PP
898If there are no shell metacharacters in the argument of \f(CW\*(C`open\*(C'\fR, Perl
899runs the command directly, without using the shell, and can correctly
900report whether the command started.
901.Sh "What's wrong with using backticks in a void context?"
902.IX Subsection "What's wrong with using backticks in a void context?"
903Strictly speaking, nothing. Stylistically speaking, it's not a good
904way to write maintainable code. Perl has several operators for
905running external commands. Backticks are one; they collect the output
906from the command for use in your program. The \f(CW\*(C`system\*(C'\fR function is
907another; it doesn't do this.
908.PP
909Writing backticks in your program sends a clear message to the readers
910of your code that you wanted to collect the output of the command.
911Why send a clear message that isn't true?
912.PP
913Consider this line:
914.PP
915.Vb 1
916\& `cat /etc/termcap`;
917.Ve
918.PP
919You forgot to check \f(CW$?\fR to see whether the program even ran
920correctly. Even if you wrote
921.PP
922.Vb 1
923\& print `cat /etc/termcap`;
924.Ve
925.PP
926this code could and probably should be written as
927.PP
928.Vb 2
929\& system("cat /etc/termcap") == 0
930\& or die "cat program failed!";
931.Ve
932.PP
933which will get the output quickly (as it is generated, instead of only
934at the end) and also check the return value.
935.PP
936\&\fIsystem()\fR also provides direct control over whether shell wildcard
937processing may take place, whereas backticks do not.
938.Sh "How can I call backticks without shell processing?"
939.IX Subsection "How can I call backticks without shell processing?"
940This is a bit tricky. Instead of writing
941.PP
942.Vb 1
943\& @ok = `grep @opts '$search_string' @filenames`;
944.Ve
945.PP
946You have to do this:
947.PP
948.Vb 10
949\& my @ok = ();
950\& if (open(GREP, "-|")) {
951\& while (<GREP>) {
952\& chomp;
953\& push(@ok, $_);
954\& }
955\& close GREP;
956\& } else {
957\& exec 'grep', @opts, $search_string, @filenames;
958\& }
959.Ve
960.PP
961Just as with \fIsystem()\fR, no shell escapes happen when you \fIexec()\fR a list.
962Further examples of this can be found in \*(L"Safe Pipe Opens\*(R" in perlipc.
963.PP
964Note that if you're stuck on Microsoft, no solution to this vexing issue
965is even possible. Even if Perl were to emulate \fIfork()\fR, you'd still
966be hosed, because Microsoft gives no argc/argv\-style \s-1API\s0. Their \s-1API\s0
967always reparses from a single string, which is fundamentally wrong,
968but you're not likely to get the Gods of Redmond to acknowledge this
969and fix it for you.
970.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)?"
971.IX Subsection "Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?"
972Some stdio's set error and eof flags that need clearing. The
973\&\s-1POSIX\s0 module defines \fIclearerr()\fR that you can use. That is the
974technically correct way to do it. Here are some less reliable
975workarounds:
976.IP "1" 4
977.IX Item "1"
978Try keeping around the seekpointer and go there, like this:
979.Sp
980.Vb 2
981\& $where = tell(LOG);
982\& seek(LOG, $where, 0);
983.Ve
984.IP "2" 4
985.IX Item "2"
986If that doesn't work, try seeking to a different part of the file and
987then back.
988.IP "3" 4
989.IX Item "3"
990If that doesn't work, try seeking to a different part of
991the file, reading something, and then seeking back.
992.IP "4" 4
993.IX Item "4"
994If that doesn't work, give up on your stdio package and use sysread.
995.Sh "How can I convert my shell script to perl?"
996.IX Subsection "How can I convert my shell script to perl?"
997Learn Perl and rewrite it. Seriously, there's no simple converter.
998Things that are awkward to do in the shell are easy to do in Perl, and
999this very awkwardness is what would make a shell\->perl converter
1000nigh-on impossible to write. By rewriting it, you'll think about what
1001you're really trying to do, and hopefully will escape the shell's
1002pipeline datastream paradigm, which while convenient for some matters,
1003causes many inefficiencies.
1004.Sh "Can I use perl to run a telnet or ftp session?"
1005.IX Subsection "Can I use perl to run a telnet or ftp session?"
1006Try the Net::FTP, TCP::Client, and Net::Telnet modules (available from
1007\&\s-1CPAN\s0). http://www.cpan.org/scripts/netstuff/telnet.emul.shar
1008will also help for emulating the telnet protocol, but Net::Telnet is
1009quite probably easier to use..
1010.PP
1011If all you want to do is pretend to be telnet but don't need
1012the initial telnet handshaking, then the standard dual-process
1013approach will suffice:
1014.PP
1015.Vb 12
1016\& use IO::Socket; # new in 5.004
1017\& $handle = IO::Socket::INET->new('www.perl.com:80')
1018\& || die "can't connect to port 80 on www.perl.com: $!";
1019\& $handle->autoflush(1);
1020\& if (fork()) { # XXX: undef means failure
1021\& select($handle);
1022\& print while <STDIN>; # everything from stdin to socket
1023\& } else {
1024\& print while <$handle>; # everything from socket to stdout
1025\& }
1026\& close $handle;
1027\& exit;
1028.Ve
1029.Sh "How can I write expect in Perl?"
1030.IX Subsection "How can I write expect in Perl?"
1031Once upon a time, there was a library called chat2.pl (part of the
1032standard perl distribution), which never really got finished. If you
1033find it somewhere, \fIdon't use it\fR. These days, your best bet is to
1034look at the Expect module available from \s-1CPAN\s0, which also requires two
1035other modules from \s-1CPAN\s0, IO::Pty and IO::Stty.
1036.ie n .Sh "Is there a way to hide perl's command line from programs such as ""ps""?"
1037.el .Sh "Is there a way to hide perl's command line from programs such as ``ps''?"
1038.IX Subsection "Is there a way to hide perl's command line from programs such as ps?"
1039First of all note that if you're doing this for security reasons (to
1040avoid people seeing passwords, for example) then you should rewrite
1041your program so that critical information is never given as an
1042argument. Hiding the arguments won't make your program completely
1043secure.
1044.PP
1045To actually alter the visible command line, you can assign to the
1046variable \f(CW$0\fR as documented in perlvar. This won't work on all
1047operating systems, though. Daemon programs like sendmail place their
1048state there, as in:
1049.PP
1050.Vb 1
1051\& $0 = "orcus [accepting connections]";
1052.Ve
1053.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?"
1054.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?"
1055.IP "Unix" 4
1056.IX Item "Unix"
1057In the strictest sense, it can't be done\*(--the script executes as a
1058different process from the shell it was started from. Changes to a
1059process are not reflected in its parent\*(--only in any children
1060created after the change. There is shell magic that may allow you to
1061fake it by \fIeval()\fRing the script's output in your shell; check out the
1062comp.unix.questions \s-1FAQ\s0 for details.
1063.Sh "How do I close a process's filehandle without waiting for it to complete?"
1064.IX Subsection "How do I close a process's filehandle without waiting for it to complete?"
1065Assuming your system supports such things, just send an appropriate signal
1066to the process (see \*(L"kill\*(R" in perlfunc). It's common to first send a \s-1TERM\s0
1067signal, wait a little bit, and then send a \s-1KILL\s0 signal to finish it off.
1068.Sh "How do I fork a daemon process?"
1069.IX Subsection "How do I fork a daemon process?"
1070If by daemon process you mean one that's detached (disassociated from
1071its tty), then the following process is reported to work on most
1072Unixish systems. Non-Unix users should check their Your_OS::Process
1073module for other solutions.
1074.IP "\(bu" 4
1075Open /dev/tty and use the \s-1TIOCNOTTY\s0 ioctl on it. See \fItty\fR\|(4)
1076for details. Or better yet, you can just use the \fIPOSIX::setsid()\fR
1077function, so you don't have to worry about process groups.
1078.IP "\(bu" 4
1079Change directory to /
1080.IP "\(bu" 4
1081Reopen \s-1STDIN\s0, \s-1STDOUT\s0, and \s-1STDERR\s0 so they're not connected to the old
1082tty.
1083.IP "\(bu" 4
1084Background yourself like this:
1085.Sp
1086.Vb 1
1087\& fork && exit;
1088.Ve
1089.PP
1090The Proc::Daemon module, available from \s-1CPAN\s0, provides a function to
1091perform these actions for you.
1092.Sh "How do I find out if I'm running interactively or not?"
1093.IX Subsection "How do I find out if I'm running interactively or not?"
1094Good question. Sometimes \f(CW\*(C`\-t STDIN\*(C'\fR and \f(CW\*(C`\-t STDOUT\*(C'\fR can give clues,
1095sometimes not.
1096.PP
1097.Vb 3
1098\& if (-t STDIN && -t STDOUT) {
1099\& print "Now what? ";
1100\& }
1101.Ve
1102.PP
1103On \s-1POSIX\s0 systems, you can test whether your own process group matches
1104the current process group of your controlling terminal as follows:
1105.PP
1106.Vb 9
1107\& use POSIX qw/getpgrp tcgetpgrp/;
1108\& open(TTY, "/dev/tty") or die $!;
1109\& $tpgrp = tcgetpgrp(fileno(*TTY));
1110\& $pgrp = getpgrp();
1111\& if ($tpgrp == $pgrp) {
1112\& print "foreground\en";
1113\& } else {
1114\& print "background\en";
1115\& }
1116.Ve
1117.Sh "How do I timeout a slow event?"
1118.IX Subsection "How do I timeout a slow event?"
1119Use the \fIalarm()\fR function, probably in conjunction with a signal
1120handler, as documented in \*(L"Signals\*(R" in perlipc and the section on
1121``Signals'' in the Camel. You may instead use the more flexible
1122Sys::AlarmCall module available from \s-1CPAN\s0.
1123.Sh "How do I set \s-1CPU\s0 limits?"
1124.IX Subsection "How do I set CPU limits?"
1125Use the BSD::Resource module from \s-1CPAN\s0.
1126.Sh "How do I avoid zombies on a Unix system?"
1127.IX Subsection "How do I avoid zombies on a Unix system?"
1128Use the reaper code from \*(L"Signals\*(R" in perlipc to call \fIwait()\fR when a
1129\&\s-1SIGCHLD\s0 is received, or else use the double-fork technique described
1130in \*(L"fork\*(R" in perlfunc.
1131.Sh "How do I use an \s-1SQL\s0 database?"
1132.IX Subsection "How do I use an SQL database?"
1133There are a number of excellent interfaces to \s-1SQL\s0 databases. See the
1134DBD::* modules available from http://www.cpan.org/modules/DBD .
1135A lot of information on this can be found at http://dbi.perl.org/
1136.Sh "How do I make a \fIsystem()\fP exit on control\-C?"
1137.IX Subsection "How do I make a system() exit on control-C?"
1138You can't. You need to imitate the \fIsystem()\fR call (see perlipc for
1139sample code) and then have a signal handler for the \s-1INT\s0 signal that
1140passes the signal on to the subprocess. Or you can check for it:
1141.PP
1142.Vb 2
1143\& $rc = system($cmd);
1144\& if ($rc & 127) { die "signal death" }
1145.Ve
1146.Sh "How do I open a file without blocking?"
1147.IX Subsection "How do I open a file without blocking?"
1148If you're lucky enough to be using a system that supports
1149non-blocking reads (most Unixish systems do), you need only to use the
1150O_NDELAY or O_NONBLOCK flag from the Fcntl module in conjunction with
1151\&\fIsysopen()\fR:
1152.PP
1153.Vb 3
1154\& use Fcntl;
1155\& sysopen(FH, "/tmp/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)
1156\& or die "can't open /tmp/somefile: $!":
1157.Ve
1158.Sh "How do I install a module from \s-1CPAN\s0?"
1159.IX Subsection "How do I install a module from CPAN?"
1160The easiest way is to have a module also named \s-1CPAN\s0 do it for you.
1161This module comes with perl version 5.004 and later.
1162.PP
1163.Vb 1
1164\& $ perl -MCPAN -e shell
1165.Ve
1166.PP
1167.Vb 2
1168\& cpan shell -- CPAN exploration and modules installation (v1.59_54)
1169\& ReadLine support enabled
1170.Ve
1171.PP
1172.Vb 1
1173\& cpan> install Some::Module
1174.Ve
1175.PP
1176To manually install the \s-1CPAN\s0 module, or any well-behaved \s-1CPAN\s0 module
1177for that matter, follow these steps:
1178.IP "1" 4
1179.IX Item "1"
1180Unpack the source into a temporary area.
1181.IP "2" 4
1182.IX Item "2"
1183.Vb 1
1184\& perl Makefile.PL
1185.Ve
1186.IP "3" 4
1187.IX Item "3"
1188.Vb 1
1189\& make
1190.Ve
1191.IP "4" 4
1192.IX Item "4"
1193.Vb 1
1194\& make test
1195.Ve
1196.IP "5" 4
1197.IX Item "5"
1198.Vb 1
1199\& make install
1200.Ve
1201.PP
1202If your version of perl is compiled without dynamic loading, then you
1203just need to replace step 3 (\fBmake\fR) with \fBmake perl\fR and you will
1204get a new \fIperl\fR binary with your extension linked in.
1205.PP
1206See ExtUtils::MakeMaker for more details on building extensions.
1207See also the next question, ``What's the difference between require
1208and use?''.
1209.Sh "What's the difference between require and use?"
1210.IX Subsection "What's the difference between require and use?"
1211Perl offers several different ways to include code from one file into
1212another. Here are the deltas between the various inclusion constructs:
1213.PP
1214.Vb 3
1215\& 1) do $file is like eval `cat $file`, except the former
1216\& 1.1: searches @INC and updates %INC.
1217\& 1.2: bequeaths an *unrelated* lexical scope on the eval'ed code.
1218.Ve
1219.PP
1220.Vb 3
1221\& 2) require $file is like do $file, except the former
1222\& 2.1: checks for redundant loading, skipping already loaded files.
1223\& 2.2: raises an exception on failure to find, compile, or execute $file.
1224.Ve
1225.PP
1226.Vb 3
1227\& 3) require Module is like require "Module.pm", except the former
1228\& 3.1: translates each "::" into your system's directory separator.
1229\& 3.2: primes the parser to disambiguate class Module as an indirect object.
1230.Ve
1231.PP
1232.Vb 3
1233\& 4) use Module is like require Module, except the former
1234\& 4.1: loads the module at compile time, not run-time.
1235\& 4.2: imports symbols and semantics from that package to the current one.
1236.Ve
1237.PP
1238In general, you usually want \f(CW\*(C`use\*(C'\fR and a proper Perl module.
1239.Sh "How do I keep my own module/library directory?"
1240.IX Subsection "How do I keep my own module/library directory?"
1241When you build modules, use the \s-1PREFIX\s0 option when generating
1242Makefiles:
1243.PP
1244.Vb 1
1245\& perl Makefile.PL PREFIX=/u/mydir/perl
1246.Ve
1247.PP
1248then either set the \s-1PERL5LIB\s0 environment variable before you run
1249scripts that use the modules/libraries (see perlrun) or say
1250.PP
1251.Vb 1
1252\& use lib '/u/mydir/perl';
1253.Ve
1254.PP
1255This is almost the same as
1256.PP
1257.Vb 3
1258\& BEGIN {
1259\& unshift(@INC, '/u/mydir/perl');
1260\& }
1261.Ve
1262.PP
1263except that the lib module checks for machine-dependent subdirectories.
1264See Perl's lib for more information.
1265.Sh "How do I add the directory my program lives in to the module/library search path?"
1266.IX Subsection "How do I add the directory my program lives in to the module/library search path?"
1267.Vb 3
1268\& use FindBin;
1269\& use lib "$FindBin::Bin";
1270\& use your_own_modules;
1271.Ve
1272.Sh "How do I add a directory to my include path at runtime?"
1273.IX Subsection "How do I add a directory to my include path at runtime?"
1274Here are the suggested ways of modifying your include path:
1275.PP
1276.Vb 5
1277\& the PERLLIB environment variable
1278\& the PERL5LIB environment variable
1279\& the perl -Idir command line flag
1280\& the use lib pragma, as in
1281\& use lib "$ENV{HOME}/myown_perllib";
1282.Ve
1283.PP
1284The latter is particularly useful because it knows about machine
1285dependent architectures. The lib.pm pragmatic module was first
1286included with the 5.002 release of Perl.
1287.Sh "What is socket.ph and where do I get it?"
1288.IX Subsection "What is socket.ph and where do I get it?"
1289It's a perl4\-style file defining values for system networking
1290constants. Sometimes it is built using h2ph when Perl is installed,
1291but other times it is not. Modern programs \f(CW\*(C`use Socket;\*(C'\fR instead.
1292.SH "AUTHOR AND COPYRIGHT"
1293.IX Header "AUTHOR AND COPYRIGHT"
1294Copyright (c) 1997\-2002 Tom Christiansen and Nathan Torkington.
1295All rights reserved.
1296.PP
1297This documentation is free; you can redistribute it and/or modify it
1298under the same terms as Perl itself.
1299.PP
1300Irrespective of its distribution, all code examples in this file
1301are hereby placed into the public domain. You are permitted and
1302encouraged to use this code in your own programs for fun
1303or for profit as you see fit. A simple comment in the code giving
1304credit would be courteous but is not required.