Refresh description of sprintf()
[p5sagit/p5-mst-13.2.git] / pod / perlfaq8.pod
CommitLineData
68dc0745 1=head1 NAME
2
fc36a67e 3perlfaq8 - System Interaction ($Revision: 1.21 $, $Date: 1997/04/24 22:44:19 $)
68dc0745 4
5=head1 DESCRIPTION
6
7This section of the Perl FAQ covers questions involving operating
8system interaction. This involves interprocess communication (IPC),
9control over the user-interface (keyboard, screen and pointing
10devices), and most anything else not related to data manipulation.
11
12Read the FAQs and documentation specific to the port of perl to your
46fc3d4c 13operating system (eg, L<perlvms>, L<perlplan9>, ...). These should
68dc0745 14contain more detailed information on the vagaries of your perl.
15
16=head2 How do I find out which operating system I'm running under?
17
18The $^O variable ($OSTYPE if you use English) contains the operating
19system that your perl binary was built for.
20
21=head2 How come exec() doesn't return?
22
23Because that's what it does: it replaces your currently running
24program with a different one. If you want to keep going (as is
25probably the case if you're asking this question) use system()
26instead.
27
28=head2 How do I do fancy stuff with the keyboard/screen/mouse?
29
30How you access/control keyboards, screens, and pointing devices
31("mice") is system-dependent. Try the following modules:
32
33=over 4
34
35=item Keyboard
36
37 Term::Cap Standard perl distribution
38 Term::ReadKey CPAN
39 Term::ReadLine::Gnu CPAN
40 Term::ReadLine::Perl CPAN
41 Term::Screen CPAN
42
43=item Screen
44
45 Term::Cap Standard perl distribution
46 Curses CPAN
47 Term::ANSIColor CPAN
48
49=item Mouse
50
51 Tk CPAN
52
53=back
54
55=head2 How do I ask the user for a password?
56
57(This question has nothing to do with the web. See a different
58FAQ for that.)
59
60There's an example of this in L<perlfunc/crypt>). First, you put
61the terminal into "no echo" mode, then just read the password
62normally. You may do this with an old-style ioctl() function, POSIX
63terminal control (see L<POSIX>, and Chapter 7 of the Camel), or a call
64to the B<stty> program, with varying degrees of portability.
65
66You can also do this for most systems using the Term::ReadKey module
67from CPAN, which is easier to use and in theory more portable.
68
69=head2 How do I read and write the serial port?
70
71This depends on which operating system your program is running on. In
72the case of Unix, the serial ports will be accessible through files in
73/dev; on other systems, the devices names will doubtless differ.
74Several problem areas common to all device interaction are the
75following
76
77=over 4
78
79=item lockfiles
80
81Your system may use lockfiles to control multiple access. Make sure
82you follow the correct protocol. Unpredictable behaviour can result
83from multiple processes reading from one device.
84
85=item open mode
86
87If you expect to use both read and write operations on the device,
88you'll have to open it for update (see L<perlfunc/"open"> for
89details). You may wish to open it without running the risk of
90blocking by using sysopen() and C<O_RDWR|O_NDELAY|O_NOCTTY> from the
91Fcntl module (part of the standard perl distribution). See
92L<perlfunc/"sysopen"> for more on this approach.
93
94=item end of line
95
96Some devices will be expecting a "\r" at the end of each line rather
97than a "\n". In some ports of perl, "\r" and "\n" are different from
98their usual (Unix) ASCII values of "\012" and "\015". You may have to
99give the numeric values you want directly, using octal ("\015"), hex
100("0x0D"), or as a control-character specification ("\cM").
101
102 print DEV "atv1\012"; # wrong, for some devices
103 print DEV "atv1\015"; # right, for some devices
104
105Even though with normal text files, a "\n" will do the trick, there is
106still no unified scheme for terminating a line that is portable
46fc3d4c 107between Unix, DOS/Win, and Macintosh, except to terminate I<ALL> line
68dc0745 108ends with "\015\012", and strip what you don't need from the output.
109This applies especially to socket I/O and autoflushing, discussed
110next.
111
112=item flushing output
113
114If you expect characters to get to your device when you print() them,
115you'll want to autoflush that filehandle, as in the older
116
117 use FileHandle;
118 DEV->autoflush(1);
119
120and the newer
121
122 use IO::Handle;
123 DEV->autoflush(1);
124
125You can use select() and the C<$|> variable to control autoflushing
126(see L<perlvar/$|> and L<perlfunc/select>):
127
128 $oldh = select(DEV);
129 $| = 1;
130 select($oldh);
131
132You'll also see code that does this without a temporary variable, as in
133
134 select((select(DEV), $| = 1)[0]);
135
136As mentioned in the previous item, this still doesn't work when using
137socket I/O between Unix and Macintosh. You'll need to hardcode your
138line terminators, in that case.
139
140=item non-blocking input
141
142If you are doing a blocking read() or sysread(), you'll have to
143arrange for an alarm handler to provide a timeout (see
144L<perlfunc/alarm>). If you have a non-blocking open, you'll likely
145have a non-blocking read, which means you may have to use a 4-arg
146select() to determine whether I/O is ready on that device (see
147L<perlfunc/"select">.
148
149=back
150
151=head2 How do I decode encrypted password files?
152
153You spend lots and lots of money on dedicated hardware, but this is
154bound to get you talked about.
155
156Seriously, you can't if they are Unix password files - the Unix
157password system employs one-way encryption. Programs like Crack can
158forcibly (and intelligently) try to guess passwords, but don't (can't)
159guarantee quick success.
160
161If you're worried about users selecting bad passwords, you should
162proactively check when they try to change their password (by modifying
163passwd(1), for example).
164
165=head2 How do I start a process in the background?
166
167You could use
168
169 system("cmd &")
170
171or you could use fork as documented in L<perlfunc/"fork">, with
172further examples in L<perlipc>. Some things to be aware of, if you're
173on a Unix-like system:
174
175=over 4
176
177=item STDIN, STDOUT and STDERR are shared
178
179Both the main process and the backgrounded one (the "child" process)
180share the same STDIN, STDOUT and STDERR filehandles. If both try to
181access them at once, strange things can happen. You may want to close
182or reopen these for the child. You can get around this with
183C<open>ing a pipe (see L<perlfunc/"open">) but on some systems this
184means that the child process cannot outlive the parent.
185
186=item Signals
187
188You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too.
189SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is
190sent when you write to a filehandle whose child process has closed (an
191untrapped SIGPIPE can cause your program to silently die). This is
192not an issue with C<system("cmd&")>.
193
194=item Zombies
195
196You have to be prepared to "reap" the child process when it finishes
197
198 $SIG{CHLD} = sub { wait };
199
200See L<perlipc/"Signals"> for other examples of code to do this.
201Zombies are not an issue with C<system("prog &")>.
202
203=back
204
205=head2 How do I trap control characters/signals?
206
207You don't actually "trap" a control character. Instead, that
208character generates a signal, which you then trap. Signals are
209documented in L<perlipc/"Signals"> and chapter 6 of the Camel.
210
46fc3d4c 211Be warned that very few C libraries are re-entrant. Therefore, if you
68dc0745 212attempt to print() in a handler that got invoked during another stdio
213operation your internal structures will likely be in an
214inconsistent state, and your program will dump core. You can
215sometimes avoid this by using syswrite() instead of print().
216
217Unless you're exceedingly careful, the only safe things to do inside a
218signal handler are: set a variable and exit. And in the first case,
219you should only set a variable in such a way that malloc() is not
220called (eg, by setting a variable that already has a value).
221
222For example:
223
224 $Interrupted = 0; # to ensure it has a value
225 $SIG{INT} = sub {
226 $Interrupted++;
227 syswrite(STDERR, "ouch\n", 5);
228 }
229
230However, because syscalls restart by default, you'll find that if
231you're in a "slow" call, such as E<lt>FHE<gt>, read(), connect(), or
232wait(), that the only way to terminate them is by "longjumping" out;
46fc3d4c 233that is, by raising an exception. See the time-out handler for a
68dc0745 234blocking flock() in L<perlipc/"Signals"> or chapter 6 of the Camel.
235
236=head2 How do I modify the shadow password file on a Unix system?
237
238If perl was installed correctly, the getpw*() functions described in
239L<perlfunc> provide (read-only) access to the shadow password file.
240To change the file, make a new shadow password file (the format varies
241from system to system - see L<passwd(5)> for specifics) and use
242pwd_mkdb(8) to install it (see L<pwd_mkdb(5)> for more details).
243
244=head2 How do I set the time and date?
245
246Assuming you're running under sufficient permissions, you should be
247able to set the system-wide date and time by running the date(1)
248program. (There is no way to set the time and date on a per-process
249basis.) This mechanism will work for Unix, MS-DOS, Windows, and NT;
250the VMS equivalent is C<set time>.
251
252However, if all you want to do is change your timezone, you can
253probably get away with setting an environment variable:
254
255 $ENV{TZ} = "MST7MDT"; # unixish
256 $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
257 system "trn comp.lang.perl";
258
259=head2 How can I sleep() or alarm() for under a second?
260
261If you want finer granularity than the 1 second that the sleep()
262function provides, the easiest way is to use the select() function as
263documented in L<perlfunc/"select">. If your system has itimers and
264syscall() support, you can check out the old example in
265http://www.perl.com/CPAN/doc/misc/ancient/tutorial/eg/itimers.pl .
266
267=head2 How can I measure time under a second?
268
269In general, you may not be able to. The Time::HiRes module (available
54310121 270from CPAN) provides this functionality for some systems.
68dc0745 271
272In general, you may not be able to. But if you system supports both the
273syscall() function in Perl as well as a system call like gettimeofday(2),
274then you may be able to do something like this:
275
276 require 'sys/syscall.ph';
277
278 $TIMEVAL_T = "LL";
279
280 $done = $start = pack($TIMEVAL_T, ());
281
282 syscall( &SYS_gettimeofday, $start, 0)) != -1
283 or die "gettimeofday: $!";
284
285 ##########################
286 # DO YOUR OPERATION HERE #
287 ##########################
288
289 syscall( &SYS_gettimeofday, $done, 0) != -1
290 or die "gettimeofday: $!";
291
292 @start = unpack($TIMEVAL_T, $start);
293 @done = unpack($TIMEVAL_T, $done);
294
295 # fix microseconds
296 for ($done[1], $start[1]) { $_ /= 1_000_000 }
297
298 $delta_time = sprintf "%.4f", ($done[0] + $done[1] )
299 -
300 ($start[0] + $start[1] );
301
302=head2 How can I do an atexit() or setjmp()/longjmp()? (Exception handling)
303
304Release 5 of Perl added the END block, which can be used to simulate
305atexit(). Each package's END block is called when the program or
306thread ends (see L<perlmod> manpage for more details). It isn't
307called when untrapped signals kill the program, though, so if you use
308END blocks you should also use
309
310 use sigtrap qw(die normal-signals);
311
312Perl's exception-handling mechanism is its eval() operator. You can
313use eval() as setjmp and die() as longjmp. For details of this, see
46fc3d4c 314the section on signals, especially the time-out handler for a blocking
68dc0745 315flock() in L<perlipc/"Signals"> and chapter 6 of the Camel.
316
317If exception handling is all you're interested in, try the
318exceptions.pl library (part of the standard perl distribution).
319
320If you want the atexit() syntax (and an rmexit() as well), try the
321AtExit module available from CPAN.
322
323=head2 Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean?
324
325Some Sys-V based systems, notably Solaris 2.X, redefined some of the
326standard socket constants. Since these were constant across all
327architectures, they were often hardwired into perl code. The proper
328way to deal with this is to "use Socket" to get the correct values.
329
330Note that even though SunOS and Solaris are binary compatible, these
331values are different. Go figure.
332
333=head2 How can I call my system's unique C functions from Perl?
334
335In most cases, you write an external module to do it - see the answer
336to "Where can I learn about linking C with Perl? [h2xs, xsubpp]".
337However, if the function is a system call, and your system supports
338syscall(), you can use the syscall function (documented in
339L<perlfunc>).
340
341Remember to check the modules that came with your distribution, and
342CPAN as well - someone may already have written a module to do it.
343
344=head2 Where do I get the include files to do ioctl() or syscall()?
345
346Historically, these would be generated by the h2ph tool, part of the
347standard perl distribution. This program converts cpp(1) directives
348in C header files to files containing subroutine definitions, like
349&SYS_getitimer, which you can use as arguments to your functions.
350It doesn't work perfectly, but it usually gets most of the job done.
351Simple files like F<errno.h>, F<syscall.h>, and F<socket.h> were fine,
352but the hard ones like F<ioctl.h> nearly always need to hand-edited.
353Here's how to install the *.ph files:
354
46fc3d4c 355 1. become super-user
68dc0745 356 2. cd /usr/include
357 3. h2ph *.h */*.h
358
359If your system supports dynamic loading, for reasons of portability and
360sanity you probably ought to use h2xs (also part of the standard perl
361distribution). This tool converts C header files to Perl extensions.
362See L<perlxstut> for how to get started with h2xs.
363
364If your system doesn't support dynamic loading, you still probably
365ought to use h2xs. See L<perlxstut> and L<ExtUtils::MakeMaker> for
366more information (in brief, just use B<make perl> instead of a plain
367B<make> to rebuild perl with a new static extension).
368
369=head2 Why do setuid perl scripts complain about kernel problems?
370
371Some operating systems have bugs in the kernel that make setuid
372scripts inherently insecure. Perl gives you a number of options
373(described in L<perlsec>) to work around such systems.
374
375=head2 How can I open a pipe both to and from a command?
376
377The IPC::Open2 module (part of the standard perl distribution) is an
378easy-to-use approach that internally uses pipe(), fork(), and exec()
379to do the job. Make sure you read the deadlock warnings in its
380documentation, though (see L<IPC::Open2>).
381
3fe9a6f1 382=head2 Why can't I get the output of a command with system()?
383
46fc3d4c 384You're confusing the purpose of system() and backticks (``). system()
385runs a command and returns exit status information (as a 16 bit value:
386the low 8 bits are the signal the process died from, if any, and
387the high 8 bits are the actual exit value). Backticks (``) run a
3fe9a6f1 388command and return what it sent to STDOUT.
389
46fc3d4c 390 $exit_status = system("mail-users");
391 $output_string = `ls`;
3fe9a6f1 392
68dc0745 393=head2 How can I capture STDERR from an external command?
394
395There are three basic ways of running external commands:
396
397 system $cmd; # using system()
398 $output = `$cmd`; # using backticks (``)
399 open (PIPE, "cmd |"); # using open()
400
401With system(), both STDOUT and STDERR will go the same place as the
402script's versions of these, unless the command redirects them.
403Backticks and open() read B<only> the STDOUT of your command.
404
405With any of these, you can change file descriptors before the call:
406
407 open(STDOUT, ">logfile");
408 system("ls");
409
410or you can use Bourne shell file-descriptor redirection:
411
412 $output = `$cmd 2>some_file`;
413 open (PIPE, "cmd 2>some_file |");
414
415You can also use file-descriptor redirection to make STDERR a
416duplicate of STDOUT:
417
418 $output = `$cmd 2>&1`;
419 open (PIPE, "cmd 2>&1 |");
420
421Note that you I<cannot> simply open STDERR to be a dup of STDOUT
422in your Perl program and avoid calling the shell to do the redirection.
423This doesn't work:
424
425 open(STDERR, ">&STDOUT");
426 $alloutput = `cmd args`; # stderr still escapes
427
428This fails because the open() makes STDERR go to where STDOUT was
429going at the time of the open(). The backticks then make STDOUT go to
430a string, but don't change STDERR (which still goes to the old
431STDOUT).
432
433Note that you I<must> use Bourne shell (sh(1)) redirection syntax in
434backticks, not csh(1)! Details on why Perl's system() and backtick
435and pipe opens all use the Bourne shell are in
436http://www.perl.com/CPAN/doc/FMTEYEWTK/versus/csh.whynot .
437
438You may also use the IPC::Open3 module (part of the standard perl
439distribution), but be warned that it has a different order of
440arguments from IPC::Open2 (see L<IPC::Open3>).
441
442=head2 Why doesn't open() return an error when a pipe open fails?
443
444It does, but probably not how you expect it to. On systems that
445follow the standard fork()/exec() paradigm (eg, Unix), it works like
446this: open() causes a fork(). In the parent, open() returns with the
447process ID of the child. The child exec()s the command to be piped
448to/from. The parent can't know whether the exec() was successful or
449not - all it can return is whether the fork() succeeded or not. To
450find out if the command succeeded, you have to catch SIGCHLD and
3fe9a6f1 451wait() to get the exit status. You should also catch SIGPIPE if
452you're writing to the child -- you may not have found out the exec()
453failed by the time you write. This is documented in L<perlipc>.
68dc0745 454
455On systems that follow the spawn() paradigm, open() I<might> do what
456you expect - unless perl uses a shell to start your command. In this
457case the fork()/exec() description still applies.
458
459=head2 What's wrong with using backticks in a void context?
460
461Strictly speaking, nothing. Stylistically speaking, it's not a good
462way to write maintainable code because backticks have a (potentially
463humungous) return value, and you're ignoring it. It's may also not be very
464efficient, because you have to read in all the lines of output, allocate
465memory for them, and then throw it away. Too often people are lulled
466to writing:
467
468 `cp file file.bak`;
469
470And now they think "Hey, I'll just always use backticks to run programs."
471Bad idea: backticks are for capturing a program's output; the system()
472function is for running programs.
473
474Consider this line:
475
476 `cat /etc/termcap`;
477
478You haven't assigned the output anywhere, so it just wastes memory
479(for a little while). Plus you forgot to check C<$?> to see whether
480the program even ran correctly. Even if you wrote
481
482 print `cat /etc/termcap`;
483
484In most cases, this could and probably should be written as
485
486 system("cat /etc/termcap") == 0
487 or die "cat program failed!";
488
489Which will get the output quickly (as its generated, instead of only
490at the end ) and also check the return value.
491
492system() also provides direct control over whether shell wildcard
493processing may take place, whereas backticks do not.
494
495=head2 How can I call backticks without shell processing?
496
497This is a bit tricky. Instead of writing
498
499 @ok = `grep @opts '$search_string' @filenames`;
500
501You have to do this:
502
503 my @ok = ();
504 if (open(GREP, "-|")) {
505 while (<GREP>) {
506 chomp;
507 push(@ok, $_);
508 }
509 close GREP;
510 } else {
511 exec 'grep', @opts, $search_string, @filenames;
512 }
513
514Just as with system(), no shell escapes happen when you exec() a list.
515
54310121 516=head2 Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?
68dc0745 517
518Because some stdio's set error and eof flags that need clearing. The
519POSIX module defines clearerr() that you can use. That is the
520technically correct way to do it. Here are some less reliable
521workarounds:
522
523=over 4
524
525=item 1
526
527Try keeping around the seekpointer and go there, like this:
528
529 $where = tell(LOG);
530 seek(LOG, $where, 0);
531
532=item 2
533
534If that doesn't work, try seeking to a different part of the file and
535then back.
536
537=item 3
538
539If that doesn't work, try seeking to a different part of
540the file, reading something, and then seeking back.
541
542=item 4
543
544If that doesn't work, give up on your stdio package and use sysread.
545
546=back
547
548=head2 How can I convert my shell script to perl?
549
550Learn Perl and rewrite it. Seriously, there's no simple converter.
551Things that are awkward to do in the shell are easy to do in Perl, and
552this very awkwardness is what would make a shell->perl converter
553nigh-on impossible to write. By rewriting it, you'll think about what
554you're really trying to do, and hopefully will escape the shell's
46fc3d4c 555pipeline datastream paradigm, which while convenient for some matters,
68dc0745 556causes many inefficiencies.
557
558=head2 Can I use perl to run a telnet or ftp session?
559
46fc3d4c 560Try the Net::FTP, TCP::Client, and Net::Telnet modules (available from
561CPAN). http://www.perl.com/CPAN/scripts/netstuff/telnet.emul.shar
562will also help for emulating the telnet protocol, but Net::Telnet is
563quite probably easier to use..
564
565If all you want to do is pretend to be telnet but don't need
566the initial telnet handshaking, then the standard dual-process
567approach will suffice:
568
569 use IO::Socket; # new in 5.004
570 $handle = IO::Socket::INET->new('www.perl.com:80')
571 || die "can't connect to port 80 on www.perl.com: $!";
572 $handle->autoflush(1);
573 if (fork()) { # XXX: undef means failure
574 select($handle);
575 print while <STDIN>; # everything from stdin to socket
576 } else {
577 print while <$handle>; # everything from socket to stdout
578 }
579 close $handle;
580 exit;
68dc0745 581
582=head2 How can I write expect in Perl?
583
584Once upon a time, there was a library called chat2.pl (part of the
585standard perl distribution), which never really got finished. These
586days, your best bet is to look at the Comm.pl library available from
587CPAN.
588
589=head2 Is there a way to hide perl's command line from programs such as "ps"?
590
591First of all note that if you're doing this for security reasons (to
592avoid people seeing passwords, for example) then you should rewrite
593your program so that critical information is never given as an
594argument. Hiding the arguments won't make your program completely
595secure.
596
597To actually alter the visible command line, you can assign to the
598variable $0 as documented in L<perlvar>. This won't work on all
599operating systems, though. Daemon programs like sendmail place their
600state there, as in:
601
602 $0 = "orcus [accepting connections]";
603
604=head2 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?
605
606=over 4
607
608=item Unix
609
610In the strictest sense, it can't be done -- the script executes as a
611different process from the shell it was started from. Changes to a
612process are not reflected in its parent, only in its own children
613created after the change. There is shell magic that may allow you to
614fake it by eval()ing the script's output in your shell; check out the
615comp.unix.questions FAQ for details.
616
617=item VMS
618
619Change to %ENV persist after Perl exits, but directory changes do not.
620
621=back
622
623=head2 How do I close a process's filehandle without waiting for it to complete?
624
625Assuming your system supports such things, just send an appropriate signal
626to the process (see L<perlfunc/"kill">. It's common to first send a TERM
627signal, wait a little bit, and then send a KILL signal to finish it off.
628
629=head2 How do I fork a daemon process?
630
631If by daemon process you mean one that's detached (disassociated from
632its tty), then the following process is reported to work on most
633Unixish systems. Non-Unix users should check their Your_OS::Process
634module for other solutions.
635
636=over 4
637
638=item *
639
46fc3d4c 640Open /dev/tty and use the the TIOCNOTTY ioctl on it. See L<tty(4)>
68dc0745 641for details.
642
643=item *
644
645Change directory to /
646
647=item *
648
649Reopen STDIN, STDOUT, and STDERR so they're not connected to the old
650tty.
651
652=item *
653
654Background yourself like this:
655
656 fork && exit;
657
658=back
659
660=head2 How do I make my program run with sh and csh?
661
662See the F<eg/nih> script (part of the perl source distribution).
663
68dc0745 664=head2 How do I find out if I'm running interactively or not?
665
666Good question. Sometimes C<-t STDIN> and C<-t STDOUT> can give clues,
667sometimes not.
668
669 if (-t STDIN && -t STDOUT) {
670 print "Now what? ";
671 }
672
673On POSIX systems, you can test whether your own process group matches
674the current process group of your controlling terminal as follows:
675
676 use POSIX qw/getpgrp tcgetpgrp/;
677 open(TTY, "/dev/tty") or die $!;
678 $tpgrp = tcgetpgrp(TTY);
679 $pgrp = getpgrp();
680 if ($tpgrp == $pgrp) {
681 print "foreground\n";
682 } else {
683 print "background\n";
684 }
685
686=head2 How do I timeout a slow event?
687
688Use the alarm() function, probably in conjunction with a signal
689handler, as documented L<perlipc/"Signals"> and chapter 6 of the
690Camel. You may instead use the more flexible Sys::AlarmCall module
691available from CPAN.
692
693=head2 How do I set CPU limits?
694
695Use the BSD::Resource module from CPAN.
696
697=head2 How do I avoid zombies on a Unix system?
698
699Use the reaper code from L<perlipc/"Signals"> to call wait() when a
700SIGCHLD is received, or else use the double-fork technique described
701in L<perlfunc/fork>.
702
703=head2 How do I use an SQL database?
704
705There are a number of excellent interfaces to SQL databases. See the
706DBD::* modules available from
707http://www.perl.com/CPAN/modules/dbperl/DBD .
708
709=head2 How do I make a system() exit on control-C?
710
711You can't. You need to imitate the system() call (see L<perlipc> for
712sample code) and then have a signal handler for the INT signal that
713passes the signal on to the subprocess.
714
715=head2 How do I open a file without blocking?
716
717If you're lucky enough to be using a system that supports
718non-blocking reads (most Unixish systems do), you need only to use the
719O_NDELAY or O_NONBLOCK flag from the Fcntl module in conjunction with
720sysopen():
721
722 use Fcntl;
723 sysopen(FH, "/tmp/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)
724 or die "can't open /tmp/somefile: $!":
725
726=head2 How do I install a CPAN module?
727
728The easiest way is to have the CPAN module do it for you. This module
729comes with perl version 5.004 and later. To manually install the CPAN
730module, or any well-behaved CPAN module for that matter, follow these
731steps:
732
733=over 4
734
735=item 1
736
737Unpack the source into a temporary area.
738
739=item 2
740
741 perl Makefile.PL
742
743=item 3
744
745 make
746
747=item 4
748
749 make test
750
751=item 5
752
753 make install
754
755=back
756
757If your version of perl is compiled without dynamic loading, then you
758just need to replace step 3 (B<make>) with B<make perl> and you will
759get a new F<perl> binary with your extension linked in.
760
46fc3d4c 761See L<ExtUtils::MakeMaker> for more details on building extensions,
762the question "How do I keep my own module/library directory?"
763
764=head2 How do I keep my own module/library directory?
765
766When you build modules, use the PREFIX option when generating
767Makefiles:
768
769 perl Makefile.PL PREFIX=/u/mydir/perl
770
771then either set the PERL5LIB environment variable before you run
772scripts that use the modules/libraries (see L<perlrun>) or say
773
774 use lib '/u/mydir/perl';
775
776See Perl's L<lib> for more information.
777
778=head2 How do I add the directory my program lives in to the module/library search path?
779
780 use FindBin;
781 use lib "$FindBin:Bin";
782 use your_own_modules;
783
784=head2 How do I add a directory to my include path at runtime?
785
786Here are the suggested ways of modifying your include path:
787
788 the PERLLIB environment variable
789 the PERL5LIB environment variable
790 the perl -Idir commpand line flag
791 the use lib pragma, as in
792 use lib "$ENV{HOME}/myown_perllib";
793
794The latter is particularly useful because it knows about machine
795dependent architectures. The lib.pm pragmatic module was first
796included with the 5.002 release of Perl.
68dc0745 797
fc36a67e 798=head1 How do I get one key from the terminal at a time, under POSIX?
799
800 #!/usr/bin/perl -w
801 use strict;
802 $| = 1;
803 for (1..4) {
804 my $got;
805 print "gimme: ";
806 $got = getone();
807 print "--> $got\n";
808 }
809 exit;
810
811 BEGIN {
812 use POSIX qw(:termios_h);
813
814 my ($term, $oterm, $echo, $noecho, $fd_stdin);
815
816 $fd_stdin = fileno(STDIN);
817
818 $term = POSIX::Termios->new();
819 $term->getattr($fd_stdin);
820 $oterm = $term->getlflag();
821
822 $echo = ECHO | ECHOK | ICANON;
823 $noecho = $oterm & ~$echo;
824
825 sub cbreak {
826 $term->setlflag($noecho);
827 $term->setcc(VTIME, 1);
828 $term->setattr($fd_stdin, TCSANOW);
829 }
830
831 sub cooked {
832 $term->setlflag($oterm);
833 $term->setcc(VTIME, 0);
834 $term->setattr($fd_stdin, TCSANOW);
835 }
836
837 sub getone {
838 my $key = '';
839 cbreak();
840 sysread(STDIN, $key, 1);
841 cooked();
842 return $key;
843 }
844
845 }
846 END { cooked() }
847
848=head1 AUTHOR AND COPYRIGHT
849
850Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
851All rights reserved. See L<perlfaq> for distribution information.
852 END-of-perlfaq8.pod
853echo x - perlfaq9.pod
854sed 's/^X//' >perlfaq9.pod << 'END-of-perlfaq9.pod'
855=head1 NAME
856
857perlfaq9 - Networking ($Revision: 1.17 $, $Date: 1997/04/24 22:44:29 $)
858
859=head1 DESCRIPTION
860
861This section deals with questions related to networking, the internet,
862and a few on the web.
863
864=head2 My CGI script runs from the command line but not the browser. Can you help me fix it?
865
866Sure, but you probably can't afford our contracting rates :-)
867
868Seriously, if you can demonstrate that you've read the following FAQs
869and that your problem isn't something simple that can be easily
870answered, you'll probably receive a courteous and useful reply to your
871question if you post it on comp.infosystems.www.authoring.cgi (if it's
872something to do with HTTP, HTML, or the CGI protocols). Questions that
873appear to be Perl questions but are really CGI ones that are posted to
874comp.lang.perl.misc may not be so well received.
875
876The useful FAQs are:
877
878 http://www.perl.com/perl/faq/idiots-guide.html
879 http://www3.pair.com/webthing/docs/cgi/faqs/cgifaq.shtml
880 http://www.perl.com/perl/faq/perl-cgi-faq.html
881 http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html
882 http://www.boutell.com/faq/
883
884=head2 How do I remove HTML from a string?
885
886The most correct way (albeit not the fastest) is to use HTML::Parse
887from CPAN (part of the libwww-perl distribution, which is a must-have
888module for all web hackers).
889
890Many folks attempt a simple-minded regular expression approach, like
891C<s/E<lt>.*?E<gt>//g>, but that fails in many cases because the tags
892may continue over line breaks, they may contain quoted angle-brackets,
893or HTML comment may be present. Plus folks forget to convert
894entities, like C<&lt;> for example.
895
896Here's one "simple-minded" approach, that works for most files:
897
898 #!/usr/bin/perl -p0777
899 s/<(?:[^>'"]*|(['"]).*?\1)*>//gs
900
901If you want a more complete solution, see the 3-stage striphtml
902program in
903http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/striphtml.gz
904.
905
906=head2 How do I extract URLs?
907
908A quick but imperfect approach is
909
910 #!/usr/bin/perl -n00
911 # qxurl - tchrist@perl.com
912 print "$2\n" while m{
913 < \s*
914 A \s+ HREF \s* = \s* (["']) (.*?) \1
915 \s* >
916 }gsix;
917
918This version does not adjust relative URLs, understand alternate
919bases, deal with HTML comments, deal with HREF and NAME attributes in
920the same tag, or accept URLs themselves as arguments. It also runs
921about 100x faster than a more "complete" solution using the LWP suite
922of modules, such as the
923http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/xurl.gz
924program.
925
926=head2 How do I download a file from the user's machine? How do I open a file on another machine?
927
928In the context of an HTML form, you can use what's known as
929B<multipart/form-data> encoding. The CGI.pm module (available from
930CPAN) supports this in the start_multipart_form() method, which isn't
931the same as the startform() method.
932
933=head2 How do I make a pop-up menu in HTML?
934
935Use the B<E<lt>SELECTE<gt>> and B<E<lt>OPTIONE<gt>> tags. The CGI.pm
936module (available from CPAN) supports this widget, as well as many
937others, including some that it cleverly synthesizes on its own.
938
939=head2 How do I fetch an HTML file?
940
941One approach, if you have the lynx text-based HTML browser installed
942on your system, is this:
943
944 $html_code = `lynx -source $url`;
945 $text_data = `lynx -dump $url`;
946
947The libwww-perl (LWP) modules from CPAN provide a more powerful way to
948do this. They work through proxies, and don't require lynx:
949
950 # print HTML from a URL
951 use LWP::Simple;
952 getprint "http://www.sn.no/libwww-perl/";
953
954 # print ASCII from HTML from a URL
955 use LWP::Simple;
956 use HTML::Parse;
957 use HTML::FormatText;
958 my ($html, $ascii);
959 $html = get("http://www.perl.com/");
960 defined $html
961 or die "Can't fetch HTML from http://www.perl.com/";
962 $ascii = HTML::FormatText->new->format(parse_html($html));
963 print $ascii;
964
965=head2 how do I decode or create those %-encodings on the web?
966
967Here's an example of decoding:
968
969 $string = "http://altavista.digital.com/cgi-bin/query?pg=q&what=news&fmt=.&q=%2Bcgi-bin+%2Bperl.exe";
970 $string =~ s/%([a-fA-F0-9]{2})/chr(hex($1))/ge;
971
972Encoding is a bit harder, because you can't just blindly change
973all the non-alphanumunder character (C<\W>) into their hex escapes.
974It's important that characters with special meaning like C</> and C<?>
975I<not> be translated. Probably the easiest way to get this right is
976to avoid reinventing the wheel and just use the URI::Escape module,
977which is part of the libwww-perl package (LWP) available from CPAN.
978
979=head2 How do I redirect to another page?
980
981Instead of sending back a C<Content-Type> as the headers of your
982reply, send back a C<Location:> header. Officially this should be a
983C<URI:> header, so the CGI.pm module (available from CPAN) sends back
984both:
985
986 Location: http://www.domain.com/newpage
987 URI: http://www.domain.com/newpage
988
989Note that relative URLs in these headers can cause strange effects
990because of "optimizations" that servers do.
991
992=head2 How do I put a password on my web pages?
993
994That depends. You'll need to read the documentation for your web
995server, or perhaps check some of the other FAQs referenced above.
996
997=head2 How do I edit my .htpasswd and .htgroup files with Perl?
998
999The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a
1000consistent OO interface to these files, regardless of how they're
1001stored. Databases may be text, dbm, Berkley DB or any database with a
1002DBI compatible driver. HTTPD::UserAdmin supports files used by the
1003`Basic' and `Digest' authentication schemes. Here's an example:
1004
1005 use HTTPD::UserAdmin ();
1006 HTTPD::UserAdmin
1007 ->new(DB => "/foo/.htpasswd")
1008 ->add($username => $password);
1009
1010=head2 How do I make sure users can't enter values into a form that cause my CGI script to do bad things?
1011
1012Read the CGI security FAQ, at
1013http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html, and the
1014Perl/CGI FAQ at
1015http://www.perl.com/CPAN/doc/FAQs/cgi/perl-cgi-faq.html.
1016
1017In brief: use tainting (see L<perlsec>), which makes sure that data
1018from outside your script (eg, CGI parameters) are never used in
1019C<eval> or C<system> calls. In addition to tainting, never use the
1020single-argument form of system() or exec(). Instead, supply the
1021command and arguments as a list, which prevents shell globbing.
1022
1023=head2 How do I parse an email header?
1024
1025For a quick-and-dirty solution, try this solution derived
1026from page 222 of the 2nd edition of "Programming Perl":
1027
1028 $/ = '';
1029 $header = <MSG>;
1030 $header =~ s/\n\s+/ /g; # merge continuation lines
1031 %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );
1032
1033That solution doesn't do well if, for example, you're trying to
1034maintain all the Received lines. A more complete approach is to use
1035the Mail::Header module from CPAN (part of the MailTools package).
1036
1037=head2 How do I decode a CGI form?
1038
1039A lot of people are tempted to code this up themselves, so you've
1040probably all seen a lot of code involving C<$ENV{CONTENT_LENGTH}> and
1041C<$ENV{QUERY_STRING}>. It's true that this can work, but there are
1042also a lot of versions of this floating around that are quite simply
1043broken!
1044
1045Please do not be tempted to reinvent the wheel. Instead, use the
1046CGI.pm or CGI_Lite.pm (available from CPAN), or if you're trapped in
1047the module-free land of perl1 .. perl4, you might look into cgi-lib.pl
1048(available from http://www.bio.cam.ac.uk/web/form.html).
1049
1050=head2 How do I check a valid email address?
1051
1052You can't.
1053
1054Without sending mail to the address and seeing whether it bounces (and
1055even then you face the halting problem), you cannot determine whether
1056an email address is valid. Even if you apply the email header
1057standard, you can have problems, because there are deliverable
1058addresses that aren't RFC-822 (the mail header standard) compliant,
1059and addresses that aren't deliverable which are compliant.
1060
1061Many are tempted to try to eliminate many frequently-invalid email
1062addresses with a simple regexp, such as
1063C</^[\w.-]+\@([\w.-]\.)+\w+$/>. However, this also throws out many
1064valid ones, and says nothing about potential deliverability, so is not
1065suggested. Instead, see
1066http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/ckaddr.gz ,
1067which actually checks against the full RFC spec (except for nested
1068comments), looks for addresses you may not wish to accept email to
1069(say, Bill Clinton or your postmaster), and then makes sure that the
1070hostname given can be looked up in DNS. It's not fast, but it works.
1071
1072Here's an alternative strategy used by many CGI script authors: Check
1073the email address with a simple regexp (such as the one above). If
1074the regexp matched the address, accept the address. If the regexp
1075didn't match the address, request confirmation from the user that the
1076email address they entered was correct.
1077
1078=head2 How do I decode a MIME/BASE64 string?
1079
1080The MIME-tools package (available from CPAN) handles this and a lot
1081more. Decoding BASE64 becomes as simple as:
1082
1083 use MIME::base64;
1084 $decoded = decode_base64($encoded);
1085
1086A more direct approach is to use the unpack() function's "u"
1087format after minor transliterations:
1088
1089 tr#A-Za-z0-9+/##cd; # remove non-base64 chars
1090 tr#A-Za-z0-9+/# -_#; # convert to uuencoded format
1091 $len = pack("c", 32 + 0.75*length); # compute length byte
1092 print unpack("u", $len . $_); # uudecode and print
1093
1094=head2 How do I return the user's email address?
1095
1096On systems that support getpwuid, the $E<lt> variable and the
1097Sys::Hostname module (which is part of the standard perl distribution),
1098you can probably try using something like this:
1099
1100 use Sys::Hostname;
1101 $address = sprintf('%s@%s', getpwuid($<), hostname);
1102
1103Company policies on email address can mean that this generates addresses
1104that the company's email system will not accept, so you should ask for
1105users' email addresses when this matters. Furthermore, not all systems
1106on which Perl runs are so forthcoming with this information as is Unix.
1107
1108The Mail::Util module from CPAN (part of the MailTools package) provides a
1109mailaddress() function that tries to guess the mail address of the user.
1110It makes a more intelligent guess than the code above, using information
1111given when the module was installed, but it could still be incorrect.
1112Again, the best way is often just to ask the user.
1113
1114=head2 How do I send/read mail?
1115
1116Sending mail: the Mail::Mailer module from CPAN (part of the MailTools
1117package) is UNIX-centric, while Mail::Internet uses Net::SMTP which is
1118not UNIX-centric. Reading mail: use the Mail::Folder module from CPAN
1119(part of the MailFolder package) or the Mail::Internet module from
1120CPAN (also part of the MailTools package).
1121
1122 # sending mail
1123 use Mail::Internet;
1124 use Mail::Header;
1125 # say which mail host to use
1126 $ENV{SMTPHOSTS} = 'mail.frii.com';
1127 # create headers
1128 $header = new Mail::Header;
1129 $header->add('From', 'gnat@frii.com');
1130 $header->add('Subject', 'Testing');
1131 $header->add('To', 'gnat@frii.com');
1132 # create body
1133 $body = 'This is a test, ignore';
1134 # create mail object
1135 $mail = new Mail::Internet(undef, Header => $header, Body => \[$body]);
1136 # send it
1137 $mail->smtpsend or die;
1138
1139=head2 How do I find out my hostname/domainname/IP address?
1140
1141A lot of code has historically cavalierly called the C<`hostname`>
1142program. While sometimes expedient, this isn't very portable. It's
1143one of those tradeoffs of convenience versus portability.
1144
1145The Sys::Hostname module (part of the standard perl distribution) will
1146give you the hostname after which you can find out the IP address
1147(assuming you have working DNS) with a gethostbyname() call.
1148
1149 use Socket;
1150 use Sys::Hostname;
1151 my $host = hostname();
1152 my $addr = inet_ntoa(scalar(gethostbyname($name)) || 'localhost');
1153
1154Probably the simplest way to learn your DNS domain name is to grok
1155it out of /etc/resolv.conf, at least under Unix. Of course, this
1156assumes several things about your resolv.conf configuration, including
1157that it exists.
1158
1159(We still need a good DNS domain name-learning method for non-Unix
1160systems.)
1161
1162=head2 How do I fetch a news article or the active newsgroups?
1163
1164Use the Net::NNTP or News::NNTPClient modules, both available from CPAN.
1165This can make tasks like fetching the newsgroup list as simple as:
1166
1167 perl -MNews::NNTPClient
1168 -e 'print News::NNTPClient->new->list("newsgroups")'
1169
1170=head2 How do I fetch/put an FTP file?
1171
1172LWP::Simple (available from CPAN) can fetch but not put. Net::FTP (also
1173available from CPAN) is more complex but can put as well as fetch.
1174
1175=head2 How can I do RPC in Perl?
1176
1177A DCE::RPC module is being developed (but is not yet available), and
1178will be released as part of the DCE-Perl package (available from
1179CPAN). No ONC::RPC module is known.
1180
68dc0745 1181=head1 AUTHOR AND COPYRIGHT
1182
1183Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
1184All rights reserved. See L<perlfaq> for distribution information.
fc36a67e 1185
1186END-of-perlfaq9.pod
1187exit
1188