Commit | Line | Data |
---|---|---|
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" | |
134 | perlfaq8 \- System Interaction ($Revision: 1.8 $, $Date: 2002/05/16 12:41:42 $) | |
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. | |
141 | .PP | |
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 | |
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 | |
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 | |
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 | |
196 | Or 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?" | |
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. | |
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 | |
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. | |
222 | .PP | |
223 | .Vb 4 | |
224 | \& use Term::ReadKey; | |
225 | \& ReadMode('cbreak'); | |
226 | \& $key = ReadKey(0); | |
227 | \& ReadMode('normal'); | |
228 | .Ve | |
229 | .PP | |
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). | |
234 | .PP | |
235 | .Vb 2 | |
236 | \& use HotKey; | |
237 | \& $key = readkey(); | |
238 | .Ve | |
239 | .PP | |
240 | And here's the HotKey module, which hides the somewhat mystifying calls | |
241 | to 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?" | |
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: | |
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?" | |
331 | If 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 | |
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: | |
340 | .PP | |
341 | .Vb 2 | |
342 | \& $clear_string = `clear`; | |
343 | \& print $clear_string; | |
344 | .Ve | |
345 | .PP | |
346 | If you're planning on doing other screen manipulations, like cursor | |
347 | positions, 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?" | |
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: | |
359 | .PP | |
360 | .Vb 2 | |
361 | \& use Term::ReadKey; | |
362 | \& ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize(); | |
363 | .Ve | |
364 | .PP | |
365 | This is more portable than the raw \f(CW\*(C`ioctl\*(C'\fR, but not as | |
366 | illustrative: | |
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 | |
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. | |
390 | .PP | |
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. | |
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?" | |
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"). | |
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 | |
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 perlvar/$ | |
446 | and \*(L"select\*(R" in perlfunc, or perlfaq5, ``How do I flush/unbuffer an | |
447 | output filehandle? Why must I do this?''): | |
448 | .Sp | |
449 | .Vb 3 | |
450 | \& $oldh = select(DEV); | |
451 | \& $| = 1; | |
452 | \& select($oldh); | |
453 | .Ve | |
454 | .Sp | |
455 | You'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 | |
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: | |
463 | .Sp | |
464 | .Vb 2 | |
465 | \& use IO::Handle; | |
466 | \& DEV->autoflush(1); | |
467 | .Ve | |
468 | .Sp | |
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. | |
480 | .PP | |
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: | |
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?" | |
503 | You spend lots and lots of money on dedicated hardware, but this is | |
504 | bound to get you talked about. | |
505 | .PP | |
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. | |
513 | .PP | |
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 | You could use | |
520 | .PP | |
521 | .Vb 1 | |
522 | \& system("cmd &") | |
523 | .Ve | |
524 | .PP | |
525 | or you could use fork as documented in \*(L"fork\*(R" in perlfunc, with | |
526 | further examples in perlipc. Some things to be aware of, if you're | |
527 | on 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" | |
530 | Both the main process and the backgrounded one (the \*(L"child\*(R" process) | |
531 | share the same \s-1STDIN\s0, \s-1STDOUT\s0 and \s-1STDERR\s0 filehandles. If both try to | |
532 | access them at once, strange things can happen. You may want to close | |
533 | or 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 | |
535 | means that the child process cannot outlive the parent. | |
536 | .IP "Signals" 4 | |
537 | .IX Item "Signals" | |
538 | You'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 | |
540 | sent when you write to a filehandle whose child process has closed (an | |
541 | untrapped \s-1SIGPIPE\s0 can cause your program to silently die). This is | |
542 | not an issue with \f(CW\*(C`system("cmd&")\*(C'\fR. | |
543 | .IP "Zombies" 4 | |
544 | .IX Item "Zombies" | |
545 | You 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 | |
551 | See \*(L"Signals\*(R" in perlipc for other examples of code to do this. | |
552 | Zombies 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?" | |
555 | You don't actually \*(L"trap\*(R" a control character. Instead, that character | |
556 | generates a signal which is sent to your terminal's currently | |
557 | foregrounded process group, which you then trap in your process. | |
558 | Signals are documented in \*(L"Signals\*(R" in perlipc and the | |
559 | section on ``Signals'' in the Camel. | |
560 | .PP | |
561 | Be warned that very few C libraries are re\-entrant. Therefore, if you | |
562 | attempt to \fIprint()\fR in a handler that got invoked during another stdio | |
563 | operation your internal structures will likely be in an | |
564 | inconsistent state, and your program will dump core. You can | |
565 | sometimes avoid this by using \fIsyswrite()\fR instead of \fIprint()\fR. | |
566 | .PP | |
567 | Unless you're exceedingly careful, the only safe things to do inside a | |
568 | signal handler are (1) set a variable and (2) exit. In the first case, | |
569 | you should only set a variable in such a way that \fImalloc()\fR is not | |
570 | called (eg, by setting a variable that already has a value). | |
571 | .PP | |
572 | For 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 | |
582 | However, because syscalls restart by default, you'll find that if | |
583 | you'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; | |
585 | that is, by raising an exception. See the time-out handler for a | |
586 | blocking \fIflock()\fR in \*(L"Signals\*(R" in perlipc or the section on ``Signals'' | |
587 | in 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?" | |
590 | If perl was installed correctly and your shadow library was written | |
591 | properly, the getpw*() functions described in perlfunc should in | |
592 | theory provide (read\-only) access to entries in the shadow password | |
593 | file. To change the file, make a new shadow password file (the format | |
594 | varies 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?" | |
598 | Assuming you're running under sufficient permissions, you should be | |
599 | able to set the system-wide date and time by running the \fIdate\fR\|(1) | |
600 | program. (There is no way to set the time and date on a per-process | |
601 | basis.) This mechanism will work for Unix, \s-1MS\-DOS\s0, Windows, and \s-1NT\s0; | |
602 | the \s-1VMS\s0 equivalent is \f(CW\*(C`set time\*(C'\fR. | |
603 | .PP | |
604 | However, if all you want to do is change your time zone, you can | |
605 | probably 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?" | |
614 | If you want finer granularity than the 1 second that the \fIsleep()\fR | |
615 | function provides, the easiest way is to use the \fIselect()\fR function as | |
616 | documented in \*(L"select\*(R" in perlfunc. Try the Time::HiRes and | |
617 | the BSD::Itimer modules (available from \s-1CPAN\s0, and starting from | |
618 | Perl 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?" | |
621 | In general, you may not be able to. The Time::HiRes module (available | |
622 | from \s-1CPAN\s0, and starting from Perl 5.8 part of the standard distribution) | |
623 | provides this functionality for some systems. | |
624 | .PP | |
625 | If your system supports both the \fIsyscall()\fR function in Perl as well as | |
626 | a system call like \fIgettimeofday\fR\|(2), then you may be able to do | |
627 | something 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)" | |
674 | Release 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 | |
676 | thread ends (see perlmod manpage for more details). | |
677 | .PP | |
678 | For example, you can use this to make sure your filter program | |
679 | managed 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 | |
687 | The \s-1END\s0 block isn't called when untrapped signals kill the program, | |
688 | though, 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 | |
694 | Perl's exception-handling mechanism is its \fIeval()\fR operator. You can | |
695 | use \fIeval()\fR as setjmp and \fIdie()\fR as longjmp. For details of this, see | |
696 | the 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 | |
698 | the Camel Book. | |
699 | .PP | |
700 | If exception handling is all you're interested in, try the | |
701 | exceptions.pl library (part of the standard perl distribution). | |
702 | .PP | |
703 | If you want the \fIatexit()\fR syntax (and an \fIrmexit()\fR as well), try the | |
704 | AtExit 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?" | |
708 | Some Sys-V based systems, notably Solaris 2.X, redefined some of the | |
709 | standard socket constants. Since these were constant across all | |
710 | architectures, they were often hardwired into perl code. The proper | |
711 | way to deal with this is to \*(L"use Socket\*(R" to get the correct values. | |
712 | .PP | |
713 | Note that even though SunOS and Solaris are binary compatible, these | |
714 | values 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?" | |
717 | In most cases, you write an external module to do it\*(--see the answer | |
718 | to \*(L"Where can I learn about linking C with Perl? [h2xs, xsubpp]\*(R". | |
719 | However, if the function is a system call, and your system supports | |
720 | \&\fIsyscall()\fR, you can use the syscall function (documented in | |
721 | perlfunc). | |
722 | .PP | |
723 | Remember 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()?" | |
727 | Historically, these would be generated by the h2ph tool, part of the | |
728 | standard perl distribution. This program converts \fIcpp\fR\|(1) directives | |
729 | in C header files to files containing subroutine definitions, like | |
730 | &SYS_getitimer, which you can use as arguments to your functions. | |
731 | It doesn't work perfectly, but it usually gets most of the job done. | |
732 | Simple files like \fIerrno.h\fR, \fIsyscall.h\fR, and \fIsocket.h\fR were fine, | |
733 | but the hard ones like \fIioctl.h\fR nearly always need to hand\-edited. | |
734 | Here'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 | |
742 | If your system supports dynamic loading, for reasons of portability and | |
743 | sanity you probably ought to use h2xs (also part of the standard perl | |
744 | distribution). This tool converts C header files to Perl extensions. | |
745 | See perlxstut for how to get started with h2xs. | |
746 | .PP | |
747 | If your system doesn't support dynamic loading, you still probably | |
748 | ought to use h2xs. See perlxstut and ExtUtils::MakeMaker for | |
749 | more 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?" | |
753 | Some operating systems have bugs in the kernel that make setuid | |
754 | scripts 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?" | |
758 | The IPC::Open2 module (part of the standard perl distribution) is an | |
759 | easy-to-use approach that internally uses \fIpipe()\fR, \fIfork()\fR, and \fIexec()\fR to do | |
760 | the job. Make sure you read the deadlock warnings in its documentation, | |
761 | though (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 | |
765 | You may also use the IPC::Open3 module (part of the standard perl | |
766 | distribution), but be warned that it has a different order of | |
767 | arguments 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()?" | |
770 | You're confusing the purpose of \fIsystem()\fR and backticks (``). \fIsystem()\fR | |
771 | runs a command and returns exit status information (as a 16 bit value: | |
772 | the low 7 bits are the signal the process died from, if any, and | |
773 | the high 8 bits are the actual exit value). Backticks (``) run a | |
774 | command 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?" | |
782 | There 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 | |
790 | With \fIsystem()\fR, both \s-1STDOUT\s0 and \s-1STDERR\s0 will go the same place as the | |
791 | script's \s-1STDOUT\s0 and \s-1STDERR\s0, unless the \fIsystem()\fR command redirects them. | |
792 | Backticks and \fIopen()\fR read \fBonly\fR the \s-1STDOUT\s0 of your command. | |
793 | .PP | |
794 | With 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 | |
801 | or 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 | |
808 | You can also use file-descriptor redirection to make \s-1STDERR\s0 a | |
809 | duplicate of \s-1STDOUT:\s0 | |
810 | .PP | |
811 | .Vb 2 | |
812 | \& $output = `$cmd 2>&1`; | |
813 | \& open (PIPE, "cmd 2>&1 |"); | |
814 | .Ve | |
815 | .PP | |
816 | Note that you \fIcannot\fR simply open \s-1STDERR\s0 to be a dup of \s-1STDOUT\s0 | |
817 | in your Perl program and avoid calling the shell to do the redirection. | |
818 | This doesn't work: | |
819 | .PP | |
820 | .Vb 2 | |
821 | \& open(STDERR, ">&STDOUT"); | |
822 | \& $alloutput = `cmd args`; # stderr still escapes | |
823 | .Ve | |
824 | .PP | |
825 | This fails because the \fIopen()\fR makes \s-1STDERR\s0 go to where \s-1STDOUT\s0 was | |
826 | going at the time of the \fIopen()\fR. The backticks then make \s-1STDOUT\s0 go to | |
827 | a string, but don't change \s-1STDERR\s0 (which still goes to the old | |
828 | \&\s-1STDOUT\s0). | |
829 | .PP | |
830 | Note that you \fImust\fR use Bourne shell (\fIsh\fR\|(1)) redirection syntax in | |
831 | backticks, not \fIcsh\fR\|(1)! Details on why Perl's \fIsystem()\fR and backtick | |
832 | and 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 | |
834 | Know\*(R" collection in http://www.cpan.org/olddoc/FMTEYEWTK.tgz . To | |
835 | capture 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 | |
843 | To 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 | |
851 | To 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 | |
859 | To exchange a command's \s-1STDOUT\s0 and \s-1STDERR\s0 in order to capture the \s-1STDERR\s0 | |
860 | but 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 | |
868 | To read both a command's \s-1STDOUT\s0 and its \s-1STDERR\s0 separately, it's easiest | |
869 | and safest to redirect them separately to files, and then read from those | |
870 | files 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 | |
876 | Ordering is important in all these examples. That's because the shell | |
877 | processes 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 | |
884 | The first command sends both standard out and standard error to the | |
885 | temporary file. The second command sends only the old standard output | |
886 | there, 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?" | |
889 | If the second argument to a piped \f(CW\*(C`open\*(C'\fR contains shell | |
890 | metacharacters, perl \fIfork()\fRs, then \fIexec()\fRs a shell to decode the | |
891 | metacharacters and eventually run the desired program. If the program | |
892 | couldn't be run, it's the shell that gets the message, not Perl. All | |
893 | your Perl program can find out is whether the shell itself could be | |
894 | successfully started. You can still capture the shell's \s-1STDERR\s0 and | |
895 | 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 | |
896 | IPC::Open3 module. | |
897 | .PP | |
898 | If there are no shell metacharacters in the argument of \f(CW\*(C`open\*(C'\fR, Perl | |
899 | runs the command directly, without using the shell, and can correctly | |
900 | report 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?" | |
903 | Strictly speaking, nothing. Stylistically speaking, it's not a good | |
904 | way to write maintainable code. Perl has several operators for | |
905 | running external commands. Backticks are one; they collect the output | |
906 | from the command for use in your program. The \f(CW\*(C`system\*(C'\fR function is | |
907 | another; it doesn't do this. | |
908 | .PP | |
909 | Writing backticks in your program sends a clear message to the readers | |
910 | of your code that you wanted to collect the output of the command. | |
911 | Why send a clear message that isn't true? | |
912 | .PP | |
913 | Consider this line: | |
914 | .PP | |
915 | .Vb 1 | |
916 | \& `cat /etc/termcap`; | |
917 | .Ve | |
918 | .PP | |
919 | You forgot to check \f(CW$?\fR to see whether the program even ran | |
920 | correctly. Even if you wrote | |
921 | .PP | |
922 | .Vb 1 | |
923 | \& print `cat /etc/termcap`; | |
924 | .Ve | |
925 | .PP | |
926 | this 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 | |
933 | which will get the output quickly (as it is generated, instead of only | |
934 | at the end) and also check the return value. | |
935 | .PP | |
936 | \&\fIsystem()\fR also provides direct control over whether shell wildcard | |
937 | processing 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?" | |
940 | This is a bit tricky. Instead of writing | |
941 | .PP | |
942 | .Vb 1 | |
943 | \& @ok = `grep @opts '$search_string' @filenames`; | |
944 | .Ve | |
945 | .PP | |
946 | You 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 | |
961 | Just as with \fIsystem()\fR, no shell escapes happen when you \fIexec()\fR a list. | |
962 | Further examples of this can be found in \*(L"Safe Pipe Opens\*(R" in perlipc. | |
963 | .PP | |
964 | Note that if you're stuck on Microsoft, no solution to this vexing issue | |
965 | is even possible. Even if Perl were to emulate \fIfork()\fR, you'd still | |
966 | be hosed, because Microsoft gives no argc/argv\-style \s-1API\s0. Their \s-1API\s0 | |
967 | always reparses from a single string, which is fundamentally wrong, | |
968 | but you're not likely to get the Gods of Redmond to acknowledge this | |
969 | and 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)?" | |
972 | Some 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 | |
974 | technically correct way to do it. Here are some less reliable | |
975 | workarounds: | |
976 | .IP "1" 4 | |
977 | .IX Item "1" | |
978 | Try 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" | |
986 | If that doesn't work, try seeking to a different part of the file and | |
987 | then back. | |
988 | .IP "3" 4 | |
989 | .IX Item "3" | |
990 | If that doesn't work, try seeking to a different part of | |
991 | the file, reading something, and then seeking back. | |
992 | .IP "4" 4 | |
993 | .IX Item "4" | |
994 | If 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?" | |
997 | Learn Perl and rewrite it. Seriously, there's no simple converter. | |
998 | Things that are awkward to do in the shell are easy to do in Perl, and | |
999 | this very awkwardness is what would make a shell\->perl converter | |
1000 | nigh-on impossible to write. By rewriting it, you'll think about what | |
1001 | you're really trying to do, and hopefully will escape the shell's | |
1002 | pipeline datastream paradigm, which while convenient for some matters, | |
1003 | causes 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?" | |
1006 | Try the Net::FTP, TCP::Client, and Net::Telnet modules (available from | |
1007 | \&\s-1CPAN\s0). http://www.cpan.org/scripts/netstuff/telnet.emul.shar | |
1008 | will also help for emulating the telnet protocol, but Net::Telnet is | |
1009 | quite probably easier to use.. | |
1010 | .PP | |
1011 | If all you want to do is pretend to be telnet but don't need | |
1012 | the initial telnet handshaking, then the standard dual-process | |
1013 | approach 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?" | |
1031 | Once upon a time, there was a library called chat2.pl (part of the | |
1032 | standard perl distribution), which never really got finished. If you | |
1033 | find it somewhere, \fIdon't use it\fR. These days, your best bet is to | |
1034 | look at the Expect module available from \s-1CPAN\s0, which also requires two | |
1035 | other 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?" | |
1039 | First of all note that if you're doing this for security reasons (to | |
1040 | avoid people seeing passwords, for example) then you should rewrite | |
1041 | your program so that critical information is never given as an | |
1042 | argument. Hiding the arguments won't make your program completely | |
1043 | secure. | |
1044 | .PP | |
1045 | To actually alter the visible command line, you can assign to the | |
1046 | variable \f(CW$0\fR as documented in perlvar. This won't work on all | |
1047 | operating systems, though. Daemon programs like sendmail place their | |
1048 | state 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" | |
1057 | In the strictest sense, it can't be done\*(--the script executes as a | |
1058 | different process from the shell it was started from. Changes to a | |
1059 | process are not reflected in its parent\*(--only in any children | |
1060 | created after the change. There is shell magic that may allow you to | |
1061 | fake it by \fIeval()\fRing the script's output in your shell; check out the | |
1062 | comp.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?" | |
1065 | Assuming your system supports such things, just send an appropriate signal | |
1066 | to the process (see \*(L"kill\*(R" in perlfunc). It's common to first send a \s-1TERM\s0 | |
1067 | signal, 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?" | |
1070 | If by daemon process you mean one that's detached (disassociated from | |
1071 | its tty), then the following process is reported to work on most | |
1072 | Unixish systems. Non-Unix users should check their Your_OS::Process | |
1073 | module for other solutions. | |
1074 | .IP "\(bu" 4 | |
1075 | Open /dev/tty and use the \s-1TIOCNOTTY\s0 ioctl on it. See \fItty\fR\|(4) | |
1076 | for details. Or better yet, you can just use the \fIPOSIX::setsid()\fR | |
1077 | function, so you don't have to worry about process groups. | |
1078 | .IP "\(bu" 4 | |
1079 | Change directory to / | |
1080 | .IP "\(bu" 4 | |
1081 | Reopen \s-1STDIN\s0, \s-1STDOUT\s0, and \s-1STDERR\s0 so they're not connected to the old | |
1082 | tty. | |
1083 | .IP "\(bu" 4 | |
1084 | Background yourself like this: | |
1085 | .Sp | |
1086 | .Vb 1 | |
1087 | \& fork && exit; | |
1088 | .Ve | |
1089 | .PP | |
1090 | The Proc::Daemon module, available from \s-1CPAN\s0, provides a function to | |
1091 | perform 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?" | |
1094 | Good question. Sometimes \f(CW\*(C`\-t STDIN\*(C'\fR and \f(CW\*(C`\-t STDOUT\*(C'\fR can give clues, | |
1095 | sometimes not. | |
1096 | .PP | |
1097 | .Vb 3 | |
1098 | \& if (-t STDIN && -t STDOUT) { | |
1099 | \& print "Now what? "; | |
1100 | \& } | |
1101 | .Ve | |
1102 | .PP | |
1103 | On \s-1POSIX\s0 systems, you can test whether your own process group matches | |
1104 | the 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?" | |
1119 | Use the \fIalarm()\fR function, probably in conjunction with a signal | |
1120 | handler, as documented in \*(L"Signals\*(R" in perlipc and the section on | |
1121 | ``Signals'' in the Camel. You may instead use the more flexible | |
1122 | Sys::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?" | |
1125 | Use 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?" | |
1128 | Use 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 | |
1130 | in \*(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?" | |
1133 | There are a number of excellent interfaces to \s-1SQL\s0 databases. See the | |
1134 | DBD::* modules available from http://www.cpan.org/modules/DBD . | |
1135 | A 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?" | |
1138 | You can't. You need to imitate the \fIsystem()\fR call (see perlipc for | |
1139 | sample code) and then have a signal handler for the \s-1INT\s0 signal that | |
1140 | passes 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?" | |
1148 | If you're lucky enough to be using a system that supports | |
1149 | non-blocking reads (most Unixish systems do), you need only to use the | |
1150 | O_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?" | |
1160 | The easiest way is to have a module also named \s-1CPAN\s0 do it for you. | |
1161 | This 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 | |
1176 | To manually install the \s-1CPAN\s0 module, or any well-behaved \s-1CPAN\s0 module | |
1177 | for that matter, follow these steps: | |
1178 | .IP "1" 4 | |
1179 | .IX Item "1" | |
1180 | Unpack 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 | |
1202 | If your version of perl is compiled without dynamic loading, then you | |
1203 | just need to replace step 3 (\fBmake\fR) with \fBmake perl\fR and you will | |
1204 | get a new \fIperl\fR binary with your extension linked in. | |
1205 | .PP | |
1206 | See ExtUtils::MakeMaker for more details on building extensions. | |
1207 | See also the next question, ``What's the difference between require | |
1208 | and use?''. | |
1209 | .Sh "What's the difference between require and use?" | |
1210 | .IX Subsection "What's the difference between require and use?" | |
1211 | Perl offers several different ways to include code from one file into | |
1212 | another. 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 | |
1238 | In 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?" | |
1241 | When you build modules, use the \s-1PREFIX\s0 option when generating | |
1242 | Makefiles: | |
1243 | .PP | |
1244 | .Vb 1 | |
1245 | \& perl Makefile.PL PREFIX=/u/mydir/perl | |
1246 | .Ve | |
1247 | .PP | |
1248 | then either set the \s-1PERL5LIB\s0 environment variable before you run | |
1249 | scripts that use the modules/libraries (see perlrun) or say | |
1250 | .PP | |
1251 | .Vb 1 | |
1252 | \& use lib '/u/mydir/perl'; | |
1253 | .Ve | |
1254 | .PP | |
1255 | This is almost the same as | |
1256 | .PP | |
1257 | .Vb 3 | |
1258 | \& BEGIN { | |
1259 | \& unshift(@INC, '/u/mydir/perl'); | |
1260 | \& } | |
1261 | .Ve | |
1262 | .PP | |
1263 | except that the lib module checks for machine-dependent subdirectories. | |
1264 | See 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?" | |
1274 | Here 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 | |
1284 | The latter is particularly useful because it knows about machine | |
1285 | dependent architectures. The lib.pm pragmatic module was first | |
1286 | included 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?" | |
1289 | It's a perl4\-style file defining values for system networking | |
1290 | constants. Sometimes it is built using h2ph when Perl is installed, | |
1291 | but 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" | |
1294 | Copyright (c) 1997\-2002 Tom Christiansen and Nathan Torkington. | |
1295 | All rights reserved. | |
1296 | .PP | |
1297 | This documentation is free; you can redistribute it and/or modify it | |
1298 | under the same terms as Perl itself. | |
1299 | .PP | |
1300 | Irrespective of its distribution, all code examples in this file | |
1301 | are hereby placed into the public domain. You are permitted and | |
1302 | encouraged to use this code in your own programs for fun | |
1303 | or for profit as you see fit. A simple comment in the code giving | |
1304 | credit would be courteous but is not required. |