Penguin
Annotated edit history of perlfaq8(1) version 2, including all changes. View license author blame.
Rev Author # Line
1 perry 1 PERLFAQ8
2 !!!PERLFAQ8
3 NAME
4 DESCRIPTION
5 AUTHOR AND COPYRIGHT
6 ----
7 !!NAME
8
9
10 perlfaq8 - System Interaction ($Revision: 1.39 $, $Date: 1999/05/23 18:37:57 $)
11 !!DESCRIPTION
12
13
14 This section of the Perl FAQ covers questions
15 involving operating system interaction. Topics include
16 interprocess communication ( IPC ), control
17 over the user-interface (keyboard, screen and pointing
18 devices), and most anything else not related to data
19 manipulation.
20
21
22 Read the FAQs and documentation specific to the port of perl
23 to your operating system (eg, perlvms, perlplan9, ...).
24 These should contain more detailed information on the
25 vagaries of your perl.
26
27
28 __How do I find out which operating system I'm running
29 under?__
30
31
32 The $^O variable ($OSNAME if you use English) contains an
33 indication of the name of the operating system (not its
34 release number) that your perl binary was built
35 for.
36
37
38 __How come__ ''exec()'' __doesn't
39 return?__
40
41
42 Because that's what it does: it replaces your currently
43 running program with a different one. If you want to keep
44 going (as is probably the case if you're asking this
45 question) use ''system()'' instead.
46
47
48 __How do I do fancy stuff with the
49 keyboard/screen/mouse?__
50
51
52 How you access/control keyboards, screens, and pointing
53 devices (``mice'') is system-dependent. Try the following
54 modules:
55
56
57 Keyboard
58
59
60 Term::Cap Standard perl distribution
2 perry 61 Term::!ReadKey CPAN
62 Term::!ReadLine::Gnu CPAN
63 Term::!ReadLine::Perl CPAN
1 perry 64 Term::Screen CPAN
65
66
67 Screen
68
69
70 Term::Cap Standard perl distribution
71 Curses CPAN
72 Term::ANSIColor CPAN
73
74
75 Mouse
76
77
78 Tk CPAN
79
80
81 Some of these specific cases are shown below.
82
83
84 __How do I print something out in color?__
85
86
87 In general, you don't, because you don't know whether the
88 recipient has a color-aware display device. If you know that
89 they have an ANSI terminal that understands
90 color, you can use the Term::ANSIColor module from
91 CPAN:
92
93
94 use Term::ANSIColor;
95 print color(
96 Or like this:
97
98
99 use Term::ANSIColor qw(:constants);
100 print RED,
101
102
103 __How do I read just one key without waiting for a return
104 key?__
105
106
107 Controlling input buffering is a remarkably system-dependent
108 matter. On many systems, you can just use the __stty__
109 command as shown in ``getc'' in perlfunc, but as you see,
110 that's already getting you into portability
111 snags.
112
113
114 open(TTY,
2 perry 115 The Term::!ReadKey module from CPAN offers an easy-to-use interface that should be more efficient than shelling out to __stty__ for each key. It even includes limited support for Windows.
1 perry 116
117
2 perry 118 use Term::!ReadKey;
119 !ReadMode('cbreak');
120 $key = !ReadKey(0);
121 !ReadMode('normal');
1 perry 122 However, using the code requires that you have a working C compiler and can use it to build and install a CPAN module. Here's a solution using the standard POSIX module, which is already on your systems (assuming your system supports POSIX ).
123
124
2 perry 125 use !HotKey;
1 perry 126 $key = readkey();
2 perry 127 And here's the !HotKey module, which hides the somewhat mystifying calls to manipulate the POSIX termios structures.
1 perry 128
129
2 perry 130 # !HotKey.pm
131 package !HotKey;
1 perry 132 @ISA = qw(Exporter);
133 @EXPORT = qw(cbreak cooked readkey);
134 use strict;
135 use POSIX qw(:termios_h);
136 my ($term, $oterm, $echo, $noecho, $fd_stdin);
137 $fd_stdin = fileno(STDIN);
138 $term = POSIX::Termios-
139 $echo = ECHO ECHOK ICANON;
140 $noecho = $oterm
141 sub cbreak {
142 $term-
143 sub cooked {
144 $term-
145 sub readkey {
146 my $key = '';
147 cbreak();
148 sysread(STDIN, $key, 1);
149 cooked();
150 return $key;
151 }
152 END { cooked() }
153 1;
154
155
156 __How do I check whether input is ready on the
157 keyboard?__
158
159
160 The easiest way to do this is to read a key in nonblocking
2 perry 161 mode with the Term::!ReadKey module from CPAN
1 perry 162 , passing it an argument of -1 to indicate not to
163 block:
164
165
2 perry 166 use Term::!ReadKey;
167 !ReadMode('cbreak');
168 if (defined ($char = !ReadKey(-1)) ) {
1 perry 169 # input was waiting and it was $char
170 } else {
171 # no input was waiting
172 }
2 perry 173 !ReadMode('normal'); # restore normal tty settings
1 perry 174
175
176 __How do I clear the screen?__
177
178
179 If you only have do so infrequently, use
180 system:
181
182
183 system(
184 If you have to do this a lot, save the clear string so you can print it 100 times without calling a program 100 times:
185
186
187 $clear_string = `clear`;
188 print $clear_string;
189 If you're planning on doing other screen manipulations, like cursor positions, etc, you might wish to use Term::Cap module:
190
191
192 use Term::Cap;
193 $terminal = Term::Cap-
194
195
196 __How do I get the screen size?__
197
198
2 perry 199 If you have Term::!ReadKey module installed from
1 perry 200 CPAN , you can use it to fetch the width and
201 height in characters and in pixels:
202
203
2 perry 204 use Term::!ReadKey;
205 ($wchar, $hchar, $wpixels, $hpixels) = !GetTerminalSize();
1 perry 206 This is more portable than the raw ioctl, but not as illustrative:
207
208
209 require 'sys/ioctl.ph';
210 die
211
212
213 __How do I ask the user for a password?__
214
215
216 (This question has nothing to do with the web. See a
217 different FAQ for that.)
218
219
220 There's an example of this in ``crypt'' in perlfunc). First,
221 you put the terminal into ``no echo'' mode, then just read
222 the password normally. You may do this with an old-style
223 ''ioctl()'' function, POSIX terminal
224 control (see POSIX or its documentation the
225 Camel Book), or a call to the __stty__ program, with
226 varying degrees of portability.
227
228
229 You can also do this for most systems using the
2 perry 230 Term::!ReadKey module from CPAN , which is
1 perry 231 easier to use and in theory more portable.
232
233
2 perry 234 use Term::!ReadKey;
235 !ReadMode('noecho');
236 $password = !ReadLine(0);
1 perry 237
238
239 __How do I read and write the serial port?__
240
241
242 This depends on which operating system your program is
243 running on. In the case of Unix, the serial ports will be
244 accessible through files in /dev; on other systems, device
245 names will doubtless differ. Several problem areas common to
246 all device interaction are the following:
247
248
249 lockfiles
250
251
252 Your system may use lockfiles to control multiple access.
253 Make sure you follow the correct protocol. Unpredictable
254 behavior can result from multiple processes reading from one
255 device.
256
257
258 open mode
259
260
261 If you expect to use both read and write operations on the
262 device, you'll have to open it for update (see ``open'' in
263 perlfunc for details). You may wish to open it without
264 running the risk of blocking by using ''sysopen()'' and
265 O_RDWRO_NDELAYO_NOCTTY from the Fcntl module (part
266 of the standard perl distribution). See ``sysopen'' in
267 perlfunc for more on this approach.
268
269
270 end of line
271
272
273 Some devices will be expecting a ``r'' at the end of each
274 line rather than a ``n''. In some ports of perl, ``r'' and
275 ``n'' are different from their usual (Unix)
276 ASCII values of ``012'' and ``015''. You may
277 have to give the numeric values you want directly, using
278 octal (``015''), hex (``0x0D''), or as a control-character
279 specification (``cM'').
280
281
282 print DEV
283 Even though with normal text files a ``n'' will do the trick, there is still no unified scheme for terminating a line that is portable between Unix, DOS/Win, and Macintosh, except to terminate ''ALL'' line ends with ``015012'', and strip what you don't need from the output. This applies especially to socket I/O and autoflushing, discussed next.
284
285
286 flushing output
287
288
289 If you expect characters to get to your device when you
290 ''print()'' them, you'll want to autoflush that
291 filehandle. You can use ''select()'' and the $
292 variable to control autoflushing (see perlvar/$ and
293 ``select'' in perlfunc, or perlfaq5, ``How do I
294 flush/unbuffer an output filehandle? Why must I do
295 this?''):
296
297
298 $oldh = select(DEV);
299 $ = 1;
300 select($oldh);
301 You'll also see code that does this without a temporary variable, as in
302
303
304 select((select(DEV), $ = 1)[[0]);
305 Or if you don't mind pulling in a few thousand lines of code just because you're afraid of a little $ variable:
306
307
308 use IO::Handle;
309 DEV-
310 As mentioned in the previous item, this still doesn't work when using socket I/O between Unix and Macintosh. You'll need to hardcode your line terminators, in that case.
311
312
313 non-blocking input
314
315
316 If you are doing a blocking ''read()'' or
317 ''sysread()'', you'll have to arrange for an alarm
318 handler to provide a timeout (see ``alarm'' in perlfunc). If
319 you have a non-blocking open, you'll likely have a
320 non-blocking read, which means you may have to use a 4-arg
321 ''select()'' to determine whether I/O is ready on that
322 device (see ``select'' in perlfunc.
323
324
325 While trying to read from his caller-id box, the notorious
326 Jamie Zawinski
327 POSIX 's tcgetattr business, and various
328 other functions that go bump in the night, finally came up
329 with this:
330
331
332 sub open_modem {
333 use IPC::Open2;
334 my $stty = `/bin/stty -g`;
335 open2( *MODEM_IN, *MODEM_OUT,
336
337
338 __How do I decode encrypted password
339 files?__
340
341
342 You spend lots and lots of money on dedicated hardware, but
343 this is bound to get you talked about.
344
345
346 Seriously, you can't if they are Unix password files--the
347 Unix password system employs one-way encryption. It's more
348 like hashing than encryption. The best you can check is
349 whether something else hashes to the same string. You can't
350 turn a hash back into the original string. Programs like
351 Crack can forcibly (and intelligently) try to guess
352 passwords, but don't (can't) guarantee quick
353 success.
354
355
356 If you're worried about users selecting bad passwords, you
357 should proactively check when they try to change their
358 password (by modifying passwd(1), for
359 example).
360
361
362 __How do I start a process in the
363 background?__
364
365
366 You could use
367
368
369 system(
370 or you could use fork as documented in ``fork'' in perlfunc, with further examples in perlipc. Some things to be aware of, if you're on a Unix-like system:
371
372
373 STDIN , STDOUT , and
374 STDERR are shared
375
376
377 Both the main process and the backgrounded one (the
378 ``child'' process) share the same STDIN ,
379 STDOUT and STDERR filehandles.
380 If both try to access them at once, strange things can
381 happen. You may want to close or reopen these for the child.
382 You can get around this with opening a pipe (see
383 ``open'' in perlfunc) but on some systems this means that
384 the child process cannot outlive the parent.
385
386
387 Signals
388
389
390 You'll have to catch the SIGCHLD signal, and
391 possibly SIGPIPE too. SIGCHLD
392 is sent when the backgrounded process finishes.
393 SIGPIPE is sent when you write to a
394 filehandle whose child process has closed (an untrapped
395 SIGPIPE can cause your program to silently
396 die). This is not an issue with
397 system(.
398
399
400 Zombies
401
402
403 You have to be prepared to ``reap'' the child process when
404 it finishes
405
406
407 $SIG{CHLD} = sub { wait };
408 See ``Signals'' in perlipc for other examples of code to do this. Zombies are not an issue with system(.
409
410
411 __How do I trap control
412 characters/signals?__
413
414
415 You don't actually ``trap'' a control character. Instead,
416 that character generates a signal which is sent to your
417 terminal's currently foregrounded process group, which you
418 then trap in your process. Signals are documented in
419 ``Signals'' in perlipc and the section on ``Signals'' in the
420 Camel.
421
422
423 Be warned that very few C libraries are re-entrant.
424 Therefore, if you attempt to ''print()'' in a handler
425 that got invoked during another stdio operation your
426 internal structures will likely be in an inconsistent state,
427 and your program will dump core. You can sometimes avoid
428 this by using ''syswrite()'' instead of
429 ''print()''.
430
431
432 Unless you're exceedingly careful, the only safe things to
433 do inside a signal handler are (1) set a variable and (2)
434 exit. In the first case, you should only set a variable in
435 such a way that ''malloc()'' is not called (eg, by
436 setting a variable that already has a value).
437
438
439 For example:
440
441
442 $Interrupted = 0; # to ensure it has a value
443 $SIG{INT} = sub {
444 $Interrupted++;
445 syswrite(STDERR,
446 However, because syscalls restart by default, you'll find that if you're in a ``slow'' call, such as FH read()'', ''connect()'', or ''wait()'', that the only way to terminate them is by ``longjumping'' out; that is, by raising an exception. See the time-out handler for a blocking ''flock()'' in ``Signals'' in perlipc or the section on ``Signals'' in the Camel book.
447
448
449 __How do I modify the shadow password file on a Unix
450 system?__
451
452
453 If perl was installed correctly and your shadow library was
454 written properly, the getpw*() functions described in
455 perlfunc should in theory provide (read-only) access to
456 entries in the shadow password file. To change the file,
457 make a new shadow password file (the format varies from
458 system to system--see passwd(5) for specifics) and
459 use ''pwd_mkdb''(8) to install it (see ''pwd_mkdb''(8)
460 for more details).
461
462
463 __How do I set the time and date?__
464
465
466 Assuming you're running under sufficient permissions, you
467 should be able to set the system-wide date and time by
468 running the date(1) program. (There is no way to set
469 the time and date on a per-process basis.) This mechanism
470 will work for Unix, MS-DOS , Windows, and
471 NT ; the VMS equivalent is
472 set time.
473
474
475 However, if all you want to do is change your timezone, you
476 can probably get away with setting an environment
477 variable:
478
479
480 $ENV{TZ} =
481
482
483 __How can I__ ''sleep()'' __or__ ''alarm()''
484 __for under a second?__
485
486
487 If you want finer granularity than the 1 second that the
488 ''sleep()'' function provides, the easiest way is to use
489 the ''select()'' function as documented in ``select'' in
2 perry 490 perlfunc. Try the Time::!HiRes and the BSD::Itimer modules
1 perry 491 (available from CPAN ).
492
493
494 __How can I measure time under a second?__
495
496
2 perry 497 In general, you may not be able to. The Time::!HiRes module
1 perry 498 (available from CPAN ) provides this
499 functionality for some systems.
500
501
502 If your system supports both the ''syscall()'' function
503 in Perl as well as a system call like
504 gettimeofday(2), then you may be able to do something
505 like this:
506
507
508 require 'sys/syscall.ph';
509 $TIMEVAL_T =
510 $done = $start = pack($TIMEVAL_T, ());
511 syscall(
512 ##########################
513 # DO YOUR OPERATION HERE #
514 ##########################
515 syscall(
516 @start = unpack($TIMEVAL_T, $start);
517 @done = unpack($TIMEVAL_T, $done);
518 # fix microseconds
519 for ($done[[1], $start[[1]) { $_ /= 1_000_000 }
520 $delta_time = sprintf
521
522
523 __How can I do an__ ''atexit()'' __or__
524 ''setjmp()''__/__''longjmp()''__? (Exception
525 handling)__
526
527
528 Release 5 of Perl added the END block, which
529 can be used to simulate ''atexit()''. Each package's
530 END block is called when the program or
531 thread ends (see perlmod manpage for more
532 details).
533
534
535 For example, you can use this to make sure your filter
536 program managed to finish its output without filling up the
537 disk:
538
539
540 END {
541 close(STDOUT) die
542 The END block isn't called when untrapped signals kill the program, though, so if you use END blocks you should also use
543
544
545 use sigtrap qw(die normal-signals);
546 Perl's exception-handling mechanism is its ''eval()'' operator. You can use ''eval()'' as setjmp and ''die()'' as longjmp. For details of this, see the section on signals, especially the time-out handler for a blocking ''flock()'' in ``Signals'' in perlipc or the section on ``Signals'' in the Camel Book.
547
548
549 If exception handling is all you're interested in, try the
550 exceptions.pl library (part of the standard perl
551 distribution).
552
553
554 If you want the ''atexit()'' syntax (and an
2 perry 555 ''rmexit()'' as well), try the !AtExit module available
1 perry 556 from CPAN .
557
558
559 __Why doesn't my sockets program work under System V
560 (Solaris)? What does the error message ``Protocol not
561 supported'' mean?__
562
563
564 Some Sys-V based systems, notably Solaris 2.X, redefined
565 some of the standard socket constants. Since these were
566 constant across all architectures, they were often hardwired
567 into perl code. The proper way to deal with this is to ``use
568 Socket'' to get the correct values.
569
570
571 Note that even though SunOS and Solaris are binary
572 compatible, these values are different. Go
573 figure.
574
575
576 __How can I call my system's unique C functions from
577 Perl?__
578
579
580 In most cases, you write an external module to do it--see
581 the answer to ``Where can I learn about linking C with Perl?
582 [[h2xs, xsubpp]''. However, if the function is a system call,
583 and your system supports ''syscall()'', you can use the
584 syscall function (documented in perlfunc).
585
586
587 Remember to check the modules that came with your
588 distribution, and CPAN as well--someone may
589 already have written a module to do it.
590
591
592 __Where do I get the include files to do__ ''ioctl()''
593 __or__ ''syscall()''__?__
594
595
596 Historically, these would be generated by the h2ph tool,
597 part of the standard perl distribution. This program
598 converts cpp(1) directives in C header files to files
599 containing subroutine definitions, like
600 ''errno.h'', ''syscall.h'', and
601 ''socket.h'' were fine, but the hard ones like
602 ''ioctl.h'' nearly always need to hand-edited. Here's how
603 to install the *.ph files:
604
605
606 1. become super-user
607 2. cd /usr/include
608 3. h2ph *.h */*.h
609 If your system supports dynamic loading, for reasons of portability and sanity you probably ought to use h2xs (also part of the standard perl distribution). This tool converts C header files to Perl extensions. See perlxstut for how to get started with h2xs.
610
611
612 If your system doesn't support dynamic loading, you still
613 probably ought to use h2xs. See perlxstut and
2 perry 614 !ExtUtils::!MakeMaker for more information (in brief, just use
1 perry 615 __make perl__ instead of a plain __make__ to rebuild
616 perl with a new static extension).
617
618
619 __Why do setuid perl scripts complain about kernel
620 problems?__
621
622
623 Some operating systems have bugs in the kernel that make
624 setuid scripts inherently insecure. Perl gives you a number
625 of options (described in perlsec) to work around such
626 systems.
627
628
629 __How can I open a pipe both to and from a
630 command?__
631
632
633 The IPC::Open2 module (part of the standard perl
634 distribution) is an easy-to-use approach that internally
635 uses ''pipe()'', ''fork()'', and ''exec()'' to do
636 the job. Make sure you read the deadlock warnings in its
637 documentation, though (see IPC::Open2). See ``Bidirectional
638 Communication with Another Process'' in perlipc and
639 ``Bidirectional Communication with Yourself'' in
640 perlipc
641
642
643 You may also use the IPC::Open3 module (part of the standard
644 perl distribution), but be warned that it has a different
645 order of arguments from IPC::Open2 (see
646 IPC::Open3).
647
648
649 __Why can't I get the output of a command with__
650 ''system()''__?__
651
652
653 You're confusing the purpose of ''system()'' and
654 backticks (``). ''system()'' runs a command and returns
655 exit status information (as a 16 bit value: the low 7 bits
656 are the signal the process died from, if any, and the high 8
657 bits are the actual exit value). Backticks (``) run a
658 command and return what it sent to STDOUT
659 .
660
661
662 $exit_status = system(
663
664
665 __How can I capture STDERR from an external
666 command?__
667
668
669 There are three basic ways of running external
670 commands:
671
672
673 system $cmd; # using system()
674 $output = `$cmd`; # using backticks (``)
675 open (PIPE,
676 With ''system()'', both STDOUT and STDERR will go the same place as the script's STDOUT and STDERR , unless the ''system()'' command redirects them. Backticks and ''open()'' read __only__ the STDOUT of your command.
677
678
679 With any of these, you can change file descriptors before
680 the call:
681
682
683 open(STDOUT,
684 or you can use Bourne shell file-descriptor redirection:
685
686
687 $output = `$cmd 2
688 You can also use file-descriptor redirection to make STDERR a duplicate of STDOUT:
689
690
691 $output = `$cmd 2
692 Note that you ''cannot'' simply open STDERR to be a dup of STDOUT in your Perl program and avoid calling the shell to do the redirection. This doesn't work:
693
694
695 open(STDERR,
696 This fails because the ''open()'' makes STDERR go to where STDOUT was going at the time of the ''open()''. The backticks then make STDOUT go to a string, but don't change STDERR (which still goes to the old STDOUT ).
697
698
699 Note that you ''must'' use Bourne shell (sh(1))
700 redirection syntax in backticks, not csh(1)! Details
701 on why Perl's ''system()'' and backtick and pipe opens
702 all use the Bourne shell are in
703 http://www.perl.com/CPAN/doc/FMTEYEWTK/versus/csh.whynot .
704 To capture a command's STDERR and
705 STDOUT together:
706
707
708 $output = `cmd 2
709 To capture a command's STDOUT but discard its STDERR:
710
711
712 $output = `cmd 2
713 To capture a command's STDERR but discard its STDOUT:
714
715
716 $output = `cmd 2
717 To exchange a command's STDOUT and STDERR in order to capture the STDERR but leave its STDOUT to come out our old STDERR:
718
719
720 $output = `cmd 3
721 To read both a command's STDOUT and its STDERR separately, it's easiest and safest to redirect them separately to files, and then read from those files when the program is done:
722
723
724 system(
725 Ordering is important in all these examples. That's because the shell processes file descriptor redirections in strictly left to right order.
726
727
728 system(
729 The first command sends both standard out and standard error to the temporary file. The second command sends only the old standard output there, and the old standard error shows up on the old standard out.
730
731
732 __Why doesn't__ ''open()'' __return an error when a
733 pipe open fails?__
734
735
736 Because the pipe open takes place in two steps: first Perl
737 calls ''fork()'' to start a new process, then this new
738 process calls ''exec()'' to run the program you really
739 wanted to open. The first step reports success or failure to
740 your process, so ''open()'' can only tell you whether the
741 ''fork()'' succeeded or not.
742
743
744 To find out if the ''exec()'' step succeeded, you have to
745 catch SIGCHLD and ''wait()'' to get the
746 exit status. You should also catch SIGPIPE if
747 you're writing to the child--you may not have found out the
748 ''exec()'' failed by the time you write. This is
749 documented in perlipc.
750
751
752 In some cases, even this won't work. If the second argument
753 to a piped ''open()'' contains shell metacharacters, perl
754 ''fork()''s, then ''exec()''s a shell to decode the
755 metacharacters and eventually run the desired program. Now
756 when you call ''wait()'', you only learn whether or not
757 the ''shell'' could be successfully started...it's best
758 to avoid shell metacharacters.
759
760
761 On systems that follow the ''spawn()'' paradigm,
762 ''open() might'' do what you expect--unless perl uses a
763 shell to start your command. In this case the
764 ''fork()''/''exec()'' description still
765 applies.
766
767
768 __What's wrong with using backticks in a void
769 context?__
770
771
772 Strictly speaking, nothing. Stylistically speaking, it's not
773 a good way to write maintainable code because backticks have
774 a (potentially humongous) return value, and you're ignoring
775 it. It's may also not be very efficient, because you have to
776 read in all the lines of output, allocate memory for them,
777 and then throw it away. Too often people are lulled to
778 writing:
779
780
781 `cp file file.bak`;
782 And now they think ``Hey, I'll just always use backticks to run programs.'' Bad idea: backticks are for capturing a program's output; the ''system()'' function is for running programs.
783
784
785 Consider this line:
786
787
788 `cat /etc/termcap`;
789 You haven't assigned the output anywhere, so it just wastes memory (for a little while). You forgot to check $? to see whether the program even ran correctly, too. Even if you wrote
790
791
792 print `cat /etc/termcap`;
793 this code could and probably should be written as
794
795
796 system(
797 which will get the output quickly (as it is generated, instead of only at the end) and also check the return value.
798
799
800 ''system()'' also provides direct control over whether
801 shell wildcard processing may take place, whereas backticks
802 do not.
803
804
805 __How can I call backticks without shell
806 processing?__
807
808
809 This is a bit tricky. Instead of writing
810
811
812 @ok = `grep @opts '$search_string' @filenames`;
813 You have to do this:
814
815
816 my @ok = ();
817 if (open(GREP,
818 Just as with ''system()'', no shell escapes happen when you ''exec()'' a list. Further examples of this can be found in ``Safe Pipe Opens'' in perlipc.
819
820
821 Note that if you're stuck on Microsoft, no solution to this
822 vexing issue is even possible. Even if Perl were to emulate
823 ''fork()'', you'd still be hosed, because Microsoft gives
824 no argc/argv-style API . Their
825 API always reparses from a single string,
826 which is fundamentally wrong, but you're not likely to get
827 the Gods of Redmond to acknowledge this and fix it for
828 you.
829
830
831 __Why can't my script read from STDIN after
832 I gave it EOF (^D on Unix, ^Z on
833 MS-DOS )?__
834
835
836 Some stdio's set error and eof flags that need clearing. The
837 POSIX module defines ''clearerr()'' that
838 you can use. That is the technically correct way to do it.
839 Here are some less reliable workarounds:
840
841
842 1
843
844
845 Try keeping around the seekpointer and go there, like
846 this:
847
848
849 $where = tell(LOG);
850 seek(LOG, $where, 0);
851
852
853 2
854
855
856 If that doesn't work, try seeking to a different part of the
857 file and then back.
858
859
860 3
861
862
863 If that doesn't work, try seeking to a different part of the
864 file, reading something, and then seeking back.
865
866
867 4
868
869
870 If that doesn't work, give up on your stdio package and use
871 sysread.
872
873
874 __How can I convert my shell script to
875 perl?__
876
877
878 Learn Perl and rewrite it. Seriously, there's no simple
879 converter. Things that are awkward to do in the shell are
880 easy to do in Perl, and this very awkwardness is what would
881 make a shell-
882
883
884 __Can I use perl to run a telnet or ftp
885 session?__
886
887
888 Try the Net::FTP, TCP::Client, and Net::Telnet modules
889 (available from CPAN ).
890 http://www.perl.com/CPAN/scripts/netstuff/telnet.emul.shar
891 will also help for emulating the telnet protocol, but
892 Net::Telnet is quite probably easier to use..
893
894
895 If all you want to do is pretend to be telnet but don't need
896 the initial telnet handshaking, then the standard
897 dual-process approach will suffice:
898
899
900 use IO::Socket; # new in 5.004
901 $handle = IO::Socket::INET-
902
903
904 __How can I write expect in Perl?__
905
906
907 Once upon a time, there was a library called chat2.pl (part
908 of the standard perl distribution), which never really got
909 finished. If you find it somewhere, ''don't use it''.
910 These days, your best bet is to look at the Expect module
911 available from CPAN , which also requires two
912 other modules from CPAN , IO::Pty and
913 IO::Stty.
914
915
916 __Is there a way to hide perl's command line from programs
917 such as ``ps''?__
918
919
920 First of all note that if you're doing this for security
921 reasons (to avoid people seeing passwords, for example) then
922 you should rewrite your program so that critical information
923 is never given as an argument. Hiding the arguments won't
924 make your program completely secure.
925
926
927 To actually alter the visible command line, you can assign
928 to the variable $0 as documented in perlvar. This
929 won't work on all operating systems, though. Daemon programs
930 like sendmail place their state there, as in:
931
932
933 $0 =
934
935
936 __I {changed directory, modified my environment} in a perl
937 script. How come the change disappeared when I exited the
938 script? How do I get my changes to be
939 visible?__
940
941
942 Unix
943
944
945 In the strictest sense, it can't be done--the script
946 executes as a different process from the shell it was
947 started from. Changes to a process are not reflected in its
948 parent--only in any children created after the change. There
949 is shell magic that may allow you to fake it by
950 ''eval()''ing the script's output in your shell; check
951 out the comp.unix.questions FAQ for
952 details.
953
954
955 __How do I close a process's filehandle without waiting for
956 it to complete?__
957
958
959 Assuming your system supports such things, just send an
960 appropriate signal to the process (see ``kill'' in
961 perlfunc). It's common to first send a TERM
962 signal, wait a little bit, and then send a
963 KILL signal to finish it off.
964
965
966 __How do I fork a daemon process?__
967
968
969 If by daemon process you mean one that's detached
970 (disassociated from its tty), then the following process is
971 reported to work on most Unixish systems. Non-Unix users
972 should check their Your_OS::Process module for other
973 solutions.
974
975
976 Open /dev/tty and use the TIOCNOTTY ioctl on
977 it. See tty(4) for details. Or better yet, you can
978 just use the ''POSIX::setsid()'' function, so you don't
979 have to worry about process groups.
980
981
982 Change directory to /
983
984
985 Reopen STDIN , STDOUT , and
986 STDERR so they're not connected to the old
987 tty.
988
989
990 Background yourself like this:
991
992
993 fork
994
995
996 The Proc::Daemon module, available from CPAN
997 , provides a function to perform these actions for
998 you.
999
1000
1001 __How do I find out if I'm running interactively or
1002 not?__
1003
1004
1005 Good question. Sometimes -t STDIN and -t
1006 STDOUT can give clues, sometimes not.
1007
1008
1009 if (-t STDIN
1010 On POSIX systems, you can test whether your own process group matches the current process group of your controlling terminal as follows:
1011
1012
1013 use POSIX qw/getpgrp tcgetpgrp/;
1014 open(TTY,
1015
1016
1017 __How do I timeout a slow event?__
1018
1019
1020 Use the ''alarm()'' function, probably in conjunction
1021 with a signal handler, as documented in ``Signals'' in
1022 perlipc and the section on ``Signals'' in the Camel. You may
2 perry 1023 instead use the more flexible Sys::!AlarmCall module
1 perry 1024 available from CPAN .
1025
1026
1027 __How do I set CPU limits?__
1028
1029
1030 Use the BSD::Resource module from CPAN
1031 .
1032
1033
1034 __How do I avoid zombies on a Unix system?__
1035
1036
1037 Use the reaper code from ``Signals'' in perlipc to call
1038 ''wait()'' when a SIGCHLD is received, or
1039 else use the double-fork technique described in ``fork'' in
1040 perlfunc.
1041
1042
1043 __How do I use an SQL
1044 database?__
1045
1046
1047 There are a number of excellent interfaces to
1048 SQL databases. See the DBD::* modules
1049 available from http://www.perl.com/CPAN/modules/DBD . A lot
1050 of information on this can be found at
1051 http://www.symbolstone.org/technology/perl/DBI/
1052
1053
1054 __How do I make a__ ''system()'' __exit on
1055 control-C?__
1056
1057
1058 You can't. You need to imitate the ''system()'' call (see
1059 perlipc for sample code) and then have a signal handler for
1060 the INT signal that passes the signal on to
1061 the subprocess. Or you can check for it:
1062
1063
1064 $rc = system($cmd);
1065 if ($rc
1066
1067
1068 __How do I open a file without blocking?__
1069
1070
1071 If you're lucky enough to be using a system that supports
1072 non-blocking reads (most Unixish systems do), you need only
1073 to use the O_NDELAY or O_NONBLOCK flag from the Fcntl module
1074 in conjunction with ''sysopen()'':
1075
1076
1077 use Fcntl;
1078 sysopen(FH,
1079
1080
1081 __How do I install a module from CPAN
1082 ?__
1083
1084
1085 The easiest way is to have a module also named
1086 CPAN do it for you. This module comes with
1087 perl version 5.004 and later. To manually install the
1088 CPAN module, or any well-behaved
1089 CPAN module for that matter, follow these
1090 steps:
1091
1092
1093 1
1094
1095
1096 Unpack the source into a temporary area.
1097
1098
1099 2
1100
1101
1102 perl Makefile.PL
1103
1104
1105 3
1106
1107
1108 make
1109
1110
1111 4
1112
1113
1114 make test
1115
1116
1117 5
1118
1119
1120 make install
1121
1122
1123 If your version of perl is compiled without dynamic loading,
1124 then you just need to replace step 3 (__make__) with
1125 __make perl__ and you will get a new ''perl'' binary
1126 with your extension linked in.
1127
1128
2 perry 1129 See !ExtUtils::!MakeMaker for more details on building
1 perry 1130 extensions. See also the next question, ``What's the
1131 difference between require and use?''.
1132
1133
1134 __What's the difference between require and
1135 use?__
1136
1137
1138 Perl offers several different ways to include code from one
1139 file into another. Here are the deltas between the various
1140 inclusion constructs:
1141
1142
1143 1) do $file is like eval `cat $file`, except the former
1144 1.1: searches @INC and updates %INC.
1145 1.2: bequeaths an *unrelated* lexical scope on the eval'ed code.
1146 2) require $file is like do $file, except the former
1147 2.1: checks for redundant loading, skipping already loaded files.
1148 2.2: raises an exception on failure to find, compile, or execute $file.
1149 3) require Module is like require
1150 4) use Module is like require Module, except the former
1151 4.1: loads the module at compile time, not run-time.
1152 4.2: imports symbols and semantics from that package to the current one.
1153 In general, you usually want use and a proper Perl module.
1154
1155
1156 __How do I keep my own module/library
1157 directory?__
1158
1159
1160 When you build modules, use the PREFIX option
1161 when generating Makefiles:
1162
1163
1164 perl Makefile.PL PREFIX=/u/mydir/perl
1165 then either set the PERL5LIB environment variable before you run scripts that use the modules/libraries (see perlrun) or say
1166
1167
1168 use lib '/u/mydir/perl';
1169 This is almost the same as
1170
1171
1172 BEGIN {
1173 unshift(@INC, '/u/mydir/perl');
1174 }
1175 except that the lib module checks for machine-dependent subdirectories. See Perl's lib for more information.
1176
1177
1178 __How do I add the directory my program lives in to the
1179 module/library search path?__
1180
1181
2 perry 1182 use !FindBin;
1 perry 1183 use lib
1184
1185
1186 __How do I add a directory to my include path at
1187 runtime?__
1188
1189
1190 Here are the suggested ways of modifying your include
1191 path:
1192
1193
1194 the PERLLIB environment variable
1195 the PERL5LIB environment variable
1196 the perl -Idir command line flag
1197 the use lib pragma, as in
1198 use lib
1199 The latter is particularly useful because it knows about machine dependent architectures. The lib.pm pragmatic module was first included with the 5.002 release of Perl.
1200
1201
1202 __What is socket.ph and where do I get it?__
1203
1204
1205 It's a perl4-style file defining values for system
1206 networking constants. Sometimes it is built using h2ph when
1207 Perl is installed, but other times it is not. Modern
1208 programs use Socket; instead.
1209 !!AUTHOR AND COPYRIGHT
1210
1211
1212 Copyright (c) 1997-1999 Tom Christiansen and Nathan
1213 Torkington. All rights reserved.
1214
1215
1216 When included as part of the Standard Version of Perl, or as
1217 part of its complete documentation whether printed or
1218 otherwise, this work may be distributed only under the terms
1219 of Perl's Artistic License. Any distribution of this file or
1220 derivatives thereof ''outside'' of that package require
1221 that special arrangements be made with copyright
1222 holder.
1223
1224
1225 Irrespective of its distribution, all code examples in this
1226 file are hereby placed into the public domain. You are
1227 permitted and encouraged to use this code in your own
1228 programs for fun or for profit as you see fit. A simple
1229 comment in the code giving credit would be courteous but is
1230 not required.
1231 ----
This page is a man page (or other imported legacy content). We are unable to automatically determine the license status of this page.