1=head1 NAME
2
3perlfaq8 - System Interaction
4
5=head1 VERSION
6
7version 5.20190126
8
9=head1 DESCRIPTION
10
11This section of the Perl FAQ covers questions involving operating
12system interaction. Topics include interprocess communication (IPC),
13control over the user-interface (keyboard, screen and pointing
14devices), and most anything else not related to data manipulation.
15
16Read the FAQs and documentation specific to the port of perl to your
17operating system (eg, L<perlvms>, L<perlplan9>, ...). These should
18contain more detailed information on the vagaries of your perl.
19
20=head2 How do I find out which operating system I'm running under?
21
22The C<$^O> variable (C<$OSNAME> if you use C<English>) contains an
23indication of the name of the operating system (not its release
24number) that your perl binary was built for.
25
26=head2 How come exec() doesn't return?
27X<exec> X<system> X<fork> X<open> X<pipe>
28
29(contributed by brian d foy)
30
31The C<exec> function's job is to turn your process into another
32command and never to return. If that's not what you want to do, don't
33use C<exec>. :)
34
35If you want to run an external command and still keep your Perl process
36going, look at a piped C<open>, C<fork>, or C<system>.
37
38=head2 How do I do fancy stuff with the keyboard/screen/mouse?
39
40How you access/control keyboards, screens, and pointing devices
41("mice") is system-dependent. Try the following modules:
42
43=over 4
44
45=item Keyboard
46
47    Term::Cap               Standard perl distribution
48    Term::ReadKey           CPAN
49    Term::ReadLine::Gnu     CPAN
50    Term::ReadLine::Perl    CPAN
51    Term::Screen            CPAN
52
53=item Screen
54
55    Term::Cap               Standard perl distribution
56    Curses                  CPAN
57    Term::ANSIColor         CPAN
58
59=item Mouse
60
61    Tk                      CPAN
62    Wx                      CPAN
63    Gtk2                    CPAN
64    Qt4                     kdebindings4 package
65
66=back
67
68Some of these specific cases are shown as examples in other answers
69in this section of the perlfaq.
70
71=head2 How do I print something out in color?
72
73In general, you don't, because you don't know whether
74the recipient has a color-aware display device. If you
75know that they have an ANSI terminal that understands
76color, you can use the L<Term::ANSIColor> module from CPAN:
77
78    use Term::ANSIColor;
79    print color("red"), "Stop!\n", color("reset");
80    print color("green"), "Go!\n", color("reset");
81
82Or like this:
83
84    use Term::ANSIColor qw(:constants);
85    print RED, "Stop!\n", RESET;
86    print GREEN, "Go!\n", RESET;
87
88=head2 How do I read just one key without waiting for a return key?
89
90Controlling input buffering is a remarkably system-dependent matter.
91On many systems, you can just use the B<stty> command as shown in
92L<perlfunc/getc>, but as you see, that's already getting you into
93portability snags.
94
95    open(TTY, "+</dev/tty") or die "no tty: $!";
96    system "stty  cbreak </dev/tty >/dev/tty 2>&1";
97    $key = getc(TTY);        # perhaps this works
98    # OR ELSE
99    sysread(TTY, $key, 1);    # probably this does
100    system "stty -cbreak </dev/tty >/dev/tty 2>&1";
101
102The L<Term::ReadKey> module from CPAN offers an easy-to-use interface that
103should be more efficient than shelling out to B<stty> for each key.
104It even includes limited support for Windows.
105
106    use Term::ReadKey;
107    ReadMode('cbreak');
108    $key = ReadKey(0);
109    ReadMode('normal');
110
111However, using the code requires that you have a working C compiler
112and can use it to build and install a CPAN module. Here's a solution
113using the standard L<POSIX> module, which is already on your system
114(assuming your system supports POSIX).
115
116    use HotKey;
117    $key = readkey();
118
119And here's the C<HotKey> module, which hides the somewhat mystifying calls
120to manipulate the POSIX termios structures.
121
122    # HotKey.pm
123    package HotKey;
124
125    use strict;
126    use warnings;
127
128    use parent 'Exporter';
129    our @EXPORT = qw(cbreak cooked readkey);
130
131    use POSIX qw(:termios_h);
132    my ($term, $oterm, $echo, $noecho, $fd_stdin);
133
134    $fd_stdin = fileno(STDIN);
135    $term     = POSIX::Termios->new();
136    $term->getattr($fd_stdin);
137    $oterm     = $term->getlflag();
138
139    $echo     = ECHO | ECHOK | ICANON;
140    $noecho   = $oterm & ~$echo;
141
142    sub cbreak {
143        $term->setlflag($noecho);  # ok, so i don't want echo either
144        $term->setcc(VTIME, 1);
145        $term->setattr($fd_stdin, TCSANOW);
146    }
147
148    sub cooked {
149        $term->setlflag($oterm);
150        $term->setcc(VTIME, 0);
151        $term->setattr($fd_stdin, TCSANOW);
152    }
153
154    sub readkey {
155        my $key = '';
156        cbreak();
157        sysread(STDIN, $key, 1);
158        cooked();
159        return $key;
160    }
161
162    END { cooked() }
163
164    1;
165
166=head2 How do I check whether input is ready on the keyboard?
167
168The easiest way to do this is to read a key in nonblocking mode with the
169L<Term::ReadKey> module from CPAN, passing it an argument of -1 to indicate
170not to block:
171
172    use Term::ReadKey;
173
174    ReadMode('cbreak');
175
176    if (defined (my $char = ReadKey(-1)) ) {
177        # input was waiting and it was $char
178    } else {
179        # no input was waiting
180    }
181
182    ReadMode('normal');                  # restore normal tty settings
183
184=head2 How do I clear the screen?
185
186(contributed by brian d foy)
187
188To clear the screen, you just have to print the special sequence
189that tells the terminal to clear the screen. Once you have that
190sequence, output it when you want to clear the screen.
191
192You can use the L<Term::ANSIScreen> module to get the special
193sequence. Import the C<cls> function (or the C<:screen> tag):
194
195    use Term::ANSIScreen qw(cls);
196    my $clear_screen = cls();
197
198    print $clear_screen;
199
200The L<Term::Cap> module can also get the special sequence if you want
201to deal with the low-level details of terminal control. The C<Tputs>
202method returns the string for the given capability:
203
204    use Term::Cap;
205
206    my $terminal = Term::Cap->Tgetent( { OSPEED => 9600 } );
207    my $clear_screen = $terminal->Tputs('cl');
208
209    print $clear_screen;
210
211On Windows, you can use the L<Win32::Console> module. After creating
212an object for the output filehandle you want to affect, call the
213C<Cls> method:
214
215    Win32::Console;
216
217    my $OUT = Win32::Console->new(STD_OUTPUT_HANDLE);
218    my $clear_string = $OUT->Cls;
219
220    print $clear_screen;
221
222If you have a command-line program that does the job, you can call
223it in backticks to capture whatever it outputs so you can use it
224later:
225
226    my $clear_string = `clear`;
227
228    print $clear_string;
229
230=head2 How do I get the screen size?
231
232If you have L<Term::ReadKey> module installed from CPAN,
233you can use it to fetch the width and height in characters
234and in pixels:
235
236    use Term::ReadKey;
237    my ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
238
239This is more portable than the raw C<ioctl>, but not as
240illustrative:
241
242    require './sys/ioctl.ph';
243    die "no TIOCGWINSZ " unless defined &TIOCGWINSZ;
244    open(my $tty_fh, "+</dev/tty")                     or die "No tty: $!";
245    unless (ioctl($tty_fh, &TIOCGWINSZ, $winsize='')) {
246        die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\n", &TIOCGWINSZ;
247    }
248    my ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);
249    print "(row,col) = ($row,$col)";
250    print "  (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
251    print "\n";
252
253=head2 How do I ask the user for a password?
254
255(This question has nothing to do with the web. See a different
256FAQ for that.)
257
258There's an example of this in L<perlfunc/crypt>. First, you put the
259terminal into "no echo" mode, then just read the password normally.
260You may do this with an old-style C<ioctl()> function, POSIX terminal
261control (see L<POSIX> or its documentation the Camel Book), or a call
262to the B<stty> program, with varying degrees of portability.
263
264You can also do this for most systems using the L<Term::ReadKey> module
265from CPAN, which is easier to use and in theory more portable.
266
267    use Term::ReadKey;
268
269    ReadMode('noecho');
270    my $password = ReadLine(0);
271
272=head2 How do I read and write the serial port?
273
274This depends on which operating system your program is running on. In
275the case of Unix, the serial ports will be accessible through files in
276C</dev>; on other systems, device names will doubtless differ.
277Several problem areas common to all device interaction are the
278following:
279
280=over 4
281
282=item lockfiles
283
284Your system may use lockfiles to control multiple access. Make sure
285you follow the correct protocol. Unpredictable behavior can result
286from multiple processes reading from one device.
287
288=item open mode
289
290If you expect to use both read and write operations on the device,
291you'll have to open it for update (see L<perlfunc/"open"> for
292details). You may wish to open it without running the risk of
293blocking by using C<sysopen()> and C<O_RDWR|O_NDELAY|O_NOCTTY> from the
294L<Fcntl> module (part of the standard perl distribution). See
295L<perlfunc/"sysopen"> for more on this approach.
296
297=item end of line
298
299Some devices will be expecting a "\r" at the end of each line rather
300than a "\n". In some ports of perl, "\r" and "\n" are different from
301their usual (Unix) ASCII values of "\015" and "\012". You may have to
302give the numeric values you want directly, using octal ("\015"), hex
303("0x0D"), or as a control-character specification ("\cM").
304
305    print DEV "atv1\012";    # wrong, for some devices
306    print DEV "atv1\015";    # right, for some devices
307
308Even though with normal text files a "\n" will do the trick, there is
309still no unified scheme for terminating a line that is portable
310between Unix, DOS/Win, and Macintosh, except to terminate I<ALL> line
311ends with "\015\012", and strip what you don't need from the output.
312This applies especially to socket I/O and autoflushing, discussed
313next.
314
315=item flushing output
316
317If you expect characters to get to your device when you C<print()> them,
318you'll want to autoflush that filehandle. You can use C<select()>
319and the C<$|> variable to control autoflushing (see L<perlvar/$E<verbar>>
320and L<perlfunc/select>, or L<perlfaq5>, "How do I flush/unbuffer an
321output filehandle? Why must I do this?"):
322
323    my $old_handle = select($dev_fh);
324    $| = 1;
325    select($old_handle);
326
327You'll also see code that does this without a temporary variable, as in
328
329    select((select($deb_handle), $| = 1)[0]);
330
331Or if you don't mind pulling in a few thousand lines
332of code just because you're afraid of a little C<$|> variable:
333
334    use IO::Handle;
335    $dev_fh->autoflush(1);
336
337As mentioned in the previous item, this still doesn't work when using
338socket I/O between Unix and Macintosh. You'll need to hard code your
339line terminators, in that case.
340
341=item non-blocking input
342
343If you are doing a blocking C<read()> or C<sysread()>, you'll have to
344arrange for an alarm handler to provide a timeout (see
345L<perlfunc/alarm>). If you have a non-blocking open, you'll likely
346have a non-blocking read, which means you may have to use a 4-arg
347C<select()> to determine whether I/O is ready on that device (see
348L<perlfunc/"select">.
349
350=back
351
352While trying to read from his caller-id box, the notorious Jamie
353Zawinski C<< <jwz@netscape.com> >>, after much gnashing of teeth and
354fighting with C<sysread>, C<sysopen>, POSIX's C<tcgetattr> business,
355and various other functions that go bump in the night, finally came up
356with this:
357
358    sub open_modem {
359        use IPC::Open2;
360        my $stty = `/bin/stty -g`;
361        open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
362        # starting cu hoses /dev/tty's stty settings, even when it has
363        # been opened on a pipe...
364        system("/bin/stty $stty");
365        $_ = <MODEM_IN>;
366        chomp;
367        if ( !m/^Connected/ ) {
368            print STDERR "$0: cu printed `$_' instead of `Connected'\n";
369        }
370    }
371
372=head2 How do I decode encrypted password files?
373
374You spend lots and lots of money on dedicated hardware, but this is
375bound to get you talked about.
376
377Seriously, you can't if they are Unix password files--the Unix
378password system employs one-way encryption. It's more like hashing
379than encryption. The best you can do is check whether something else
380hashes to the same string. You can't turn a hash back into the
381original string. Programs like Crack can forcibly (and intelligently)
382try to guess passwords, but don't (can't) guarantee quick success.
383
384If you're worried about users selecting bad passwords, you should
385proactively check when they try to change their password (by modifying
386L<passwd(1)>, for example).
387
388=head2 How do I start a process in the background?
389
390(contributed by brian d foy)
391
392There's not a single way to run code in the background so you don't
393have to wait for it to finish before your program moves on to other
394tasks. Process management depends on your particular operating system,
395and many of the techniques are covered in L<perlipc>.
396
397Several CPAN modules may be able to help, including L<IPC::Open2> or
398L<IPC::Open3>, L<IPC::Run>, L<Parallel::Jobs>,
399L<Parallel::ForkManager>, L<POE>, L<Proc::Background>, and
400L<Win32::Process>. There are many other modules you might use, so
401check those namespaces for other options too.
402
403If you are on a Unix-like system, you might be able to get away with a
404system call where you put an C<&> on the end of the command:
405
406    system("cmd &")
407
408You can also try using C<fork>, as described in L<perlfunc> (although
409this is the same thing that many of the modules will do for you).
410
411=over 4
412
413=item STDIN, STDOUT, and STDERR are shared
414
415Both the main process and the backgrounded one (the "child" process)
416share the same STDIN, STDOUT and STDERR filehandles. If both try to
417access them at once, strange things can happen. You may want to close
418or reopen these for the child. You can get around this with
419C<open>ing a pipe (see L<perlfunc/"open">) but on some systems this
420means that the child process cannot outlive the parent.
421
422=item Signals
423
424You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too.
425SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is
426sent when you write to a filehandle whose child process has closed (an
427untrapped SIGPIPE can cause your program to silently die). This is
428not an issue with C<system("cmd&")>.
429
430=item Zombies
431
432You have to be prepared to "reap" the child process when it finishes.
433
434    $SIG{CHLD} = sub { wait };
435
436    $SIG{CHLD} = 'IGNORE';
437
438You can also use a double fork. You immediately C<wait()> for your
439first child, and the init daemon will C<wait()> for your grandchild once
440it exits.
441
442    unless ($pid = fork) {
443        unless (fork) {
444            exec "what you really wanna do";
445            die "exec failed!";
446        }
447        exit 0;
448    }
449    waitpid($pid, 0);
450
451See L<perlipc/"Signals"> for other examples of code to do this.
452Zombies are not an issue with C<system("prog &")>.
453
454=back
455
456=head2 How do I trap control characters/signals?
457
458You don't actually "trap" a control character. Instead, that character
459generates a signal which is sent to your terminal's currently
460foregrounded process group, which you then trap in your process.
461Signals are documented in L<perlipc/"Signals"> and the
462section on "Signals" in the Camel.
463
464You can set the values of the C<%SIG> hash to be the functions you want
465to handle the signal. After perl catches the signal, it looks in C<%SIG>
466for a key with the same name as the signal, then calls the subroutine
467value for that key.
468
469    # as an anonymous subroutine
470
471    $SIG{INT} = sub { syswrite(STDERR, "ouch\n", 5 ) };
472
473    # or a reference to a function
474
475    $SIG{INT} = \&ouch;
476
477    # or the name of the function as a string
478
479    $SIG{INT} = "ouch";
480
481Perl versions before 5.8 had in its C source code signal handlers which
482would catch the signal and possibly run a Perl function that you had set
483in C<%SIG>. This violated the rules of signal handling at that level
484causing perl to dump core. Since version 5.8.0, perl looks at C<%SIG>
485B<after> the signal has been caught, rather than while it is being caught.
486Previous versions of this answer were incorrect.
487
488=head2 How do I modify the shadow password file on a Unix system?
489
490If perl was installed correctly and your shadow library was written
491properly, the C<getpw*()> functions described in L<perlfunc> should in
492theory provide (read-only) access to entries in the shadow password
493file. To change the file, make a new shadow password file (the format
494varies from system to system--see L<passwd(1)> for specifics) and use
495C<pwd_mkdb(8)> to install it (see L<pwd_mkdb(8)> for more details).
496
497=head2 How do I set the time and date?
498
499Assuming you're running under sufficient permissions, you should be
500able to set the system-wide date and time by running the C<date(1)>
501program. (There is no way to set the time and date on a per-process
502basis.)  This mechanism will work for Unix, MS-DOS, Windows, and NT;
503the VMS equivalent is C<set time>.
504
505However, if all you want to do is change your time zone, you can
506probably get away with setting an environment variable:
507
508    $ENV{TZ} = "MST7MDT";           # Unixish
509    $ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
510    system('trn', 'comp.lang.perl.misc');
511
512=head2 How can I sleep() or alarm() for under a second?
513X<Time::HiRes> X<BSD::Itimer> X<sleep> X<select>
514
515If you want finer granularity than the 1 second that the C<sleep()>
516function provides, the easiest way is to use the C<select()> function as
517documented in L<perlfunc/"select">. Try the L<Time::HiRes> and
518the L<BSD::Itimer> modules (available from CPAN, and starting from
519Perl 5.8 L<Time::HiRes> is part of the standard distribution).
520
521=head2 How can I measure time under a second?
522X<Time::HiRes> X<BSD::Itimer> X<sleep> X<select>
523
524(contributed by brian d foy)
525
526The L<Time::HiRes> module (part of the standard distribution as of
527Perl 5.8) measures time with the C<gettimeofday()> system call, which
528returns the time in microseconds since the epoch. If you can't install
529L<Time::HiRes> for older Perls and you are on a Unixish system, you
530may be able to call C<gettimeofday(2)> directly. See
531L<perlfunc/syscall>.
532
533=head2 How can I do an atexit() or setjmp()/longjmp()? (Exception handling)
534
535You can use the C<END> block to simulate C<atexit()>. Each package's
536C<END> block is called when the program or thread ends. See the L<perlmod>
537manpage for more details about C<END> blocks.
538
539For example, you can use this to make sure your filter program managed
540to finish its output without filling up the disk:
541
542    END {
543        close(STDOUT) || die "stdout close failed: $!";
544    }
545
546The C<END> block isn't called when untrapped signals kill the program,
547though, so if you use C<END> blocks you should also use
548
549    use sigtrap qw(die normal-signals);
550
551Perl's exception-handling mechanism is its C<eval()> operator. You
552can use C<eval()> as C<setjmp> and C<die()> as C<longjmp>. For
553details of this, see the section on signals, especially the time-out
554handler for a blocking C<flock()> in L<perlipc/"Signals"> or the
555section on "Signals" in I<Programming Perl>.
556
557If exception handling is all you're interested in, use one of the
558many CPAN modules that handle exceptions, such as L<Try::Tiny>.
559
560If you want the C<atexit()> syntax (and an C<rmexit()> as well), try the
561C<AtExit> module available from CPAN.
562
563=head2 Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean?
564
565Some Sys-V based systems, notably Solaris 2.X, redefined some of the
566standard socket constants. Since these were constant across all
567architectures, they were often hardwired into perl code. The proper
568way to deal with this is to "use Socket" to get the correct values.
569
570Note that even though SunOS and Solaris are binary compatible, these
571values are different. Go figure.
572
573=head2 How can I call my system's unique C functions from Perl?
574
575In most cases, you write an external module to do it--see the answer
576to "Where can I learn about linking C with Perl? [h2xs, xsubpp]".
577However, if the function is a system call, and your system supports
578C<syscall()>, you can use the C<syscall> function (documented in
579L<perlfunc>).
580
581Remember to check the modules that came with your distribution, and
582CPAN as well--someone may already have written a module to do it. On
583Windows, try L<Win32::API>. On Macs, try L<Mac::Carbon>. If no module
584has an interface to the C function, you can inline a bit of C in your
585Perl source with L<Inline::C>.
586
587=head2 Where do I get the include files to do ioctl() or syscall()?
588
589Historically, these would be generated by the L<h2ph> tool, part of the
590standard perl distribution. This program converts C<cpp(1)> directives
591in C header files to files containing subroutine definitions, like
592C<SYS_getitimer()>, which you can use as arguments to your functions.
593It doesn't work perfectly, but it usually gets most of the job done.
594Simple files like F<errno.h>, F<syscall.h>, and F<socket.h> were fine,
595but the hard ones like F<ioctl.h> nearly always need to be hand-edited.
596Here's how to install the *.ph files:
597
598    1. Become the super-user
599    2. cd /usr/include
600    3. h2ph *.h */*.h
601
602If your system supports dynamic loading, for reasons of portability and
603sanity you probably ought to use L<h2xs> (also part of the standard perl
604distribution). This tool converts C header files to Perl extensions.
605See L<perlxstut> for how to get started with L<h2xs>.
606
607If your system doesn't support dynamic loading, you still probably
608ought to use L<h2xs>. See L<perlxstut> and L<ExtUtils::MakeMaker> for
609more information (in brief, just use B<make perl> instead of a plain
610B<make> to rebuild perl with a new static extension).
611
612=head2 Why do setuid perl scripts complain about kernel problems?
613
614Some operating systems have bugs in the kernel that make setuid
615scripts inherently insecure. Perl gives you a number of options
616(described in L<perlsec>) to work around such systems.
617
618=head2 How can I open a pipe both to and from a command?
619
620The L<IPC::Open2> module (part of the standard perl distribution) is
621an easy-to-use approach that internally uses C<pipe()>, C<fork()>, and
622C<exec()> to do the job. Make sure you read the deadlock warnings in
623its documentation, though (see L<IPC::Open2>). See
624L<perlipc/"Bidirectional Communication with Another Process"> and
625L<perlipc/"Bidirectional Communication with Yourself">
626
627You may also use the L<IPC::Open3> module (part of the standard perl
628distribution), but be warned that it has a different order of
629arguments from L<IPC::Open2> (see L<IPC::Open3>).
630
631=head2 Why can't I get the output of a command with system()?
632
633You're confusing the purpose of C<system()> and backticks (``). C<system()>
634runs a command and returns exit status information (as a 16 bit value:
635the low 7 bits are the signal the process died from, if any, and
636the high 8 bits are the actual exit value). Backticks (``) run a
637command and return what it sent to STDOUT.
638
639    my $exit_status   = system("mail-users");
640    my $output_string = `ls`;
641
642=head2 How can I capture STDERR from an external command?
643
644There are three basic ways of running external commands:
645
646    system $cmd;        # using system()
647    my $output = `$cmd`;        # using backticks (``)
648    open (my $pipe_fh, "$cmd |");    # using open()
649
650With C<system()>, both STDOUT and STDERR will go the same place as the
651script's STDOUT and STDERR, unless the C<system()> command redirects them.
652Backticks and C<open()> read B<only> the STDOUT of your command.
653
654You can also use the C<open3()> function from L<IPC::Open3>. Benjamin
655Goldberg provides some sample code:
656
657To capture a program's STDOUT, but discard its STDERR:
658
659    use IPC::Open3;
660    use File::Spec;
661    my $in = '';
662    open(NULL, ">", File::Spec->devnull);
663    my $pid = open3($in, \*PH, ">&NULL", "cmd");
664    while( <PH> ) { }
665    waitpid($pid, 0);
666
667To capture a program's STDERR, but discard its STDOUT:
668
669    use IPC::Open3;
670    use File::Spec;
671    my $in = '';
672    open(NULL, ">", File::Spec->devnull);
673    my $pid = open3($in, ">&NULL", \*PH, "cmd");
674    while( <PH> ) { }
675    waitpid($pid, 0);
676
677To capture a program's STDERR, and let its STDOUT go to our own STDERR:
678
679    use IPC::Open3;
680    my $in = '';
681    my $pid = open3($in, ">&STDERR", \*PH, "cmd");
682    while( <PH> ) { }
683    waitpid($pid, 0);
684
685To read both a command's STDOUT and its STDERR separately, you can
686redirect them to temp files, let the command run, then read the temp
687files:
688
689    use IPC::Open3;
690    use IO::File;
691    my $in = '';
692    local *CATCHOUT = IO::File->new_tmpfile;
693    local *CATCHERR = IO::File->new_tmpfile;
694    my $pid = open3($in, ">&CATCHOUT", ">&CATCHERR", "cmd");
695    waitpid($pid, 0);
696    seek $_, 0, 0 for \*CATCHOUT, \*CATCHERR;
697    while( <CATCHOUT> ) {}
698    while( <CATCHERR> ) {}
699
700But there's no real need for B<both> to be tempfiles... the following
701should work just as well, without deadlocking:
702
703    use IPC::Open3;
704    my $in = '';
705    use IO::File;
706    local *CATCHERR = IO::File->new_tmpfile;
707    my $pid = open3($in, \*CATCHOUT, ">&CATCHERR", "cmd");
708    while( <CATCHOUT> ) {}
709    waitpid($pid, 0);
710    seek CATCHERR, 0, 0;
711    while( <CATCHERR> ) {}
712
713And it'll be faster, too, since we can begin processing the program's
714stdout immediately, rather than waiting for the program to finish.
715
716With any of these, you can change file descriptors before the call:
717
718    open(STDOUT, ">logfile");
719    system("ls");
720
721or you can use Bourne shell file-descriptor redirection:
722
723    $output = `$cmd 2>some_file`;
724    open (PIPE, "cmd 2>some_file |");
725
726You can also use file-descriptor redirection to make STDERR a
727duplicate of STDOUT:
728
729    $output = `$cmd 2>&1`;
730    open (PIPE, "cmd 2>&1 |");
731
732Note that you I<cannot> simply open STDERR to be a dup of STDOUT
733in your Perl program and avoid calling the shell to do the redirection.
734This doesn't work:
735
736    open(STDERR, ">&STDOUT");
737    $alloutput = `cmd args`;  # stderr still escapes
738
739This fails because the C<open()> makes STDERR go to where STDOUT was
740going at the time of the C<open()>. The backticks then make STDOUT go to
741a string, but don't change STDERR (which still goes to the old
742STDOUT).
743
744Note that you I<must> use Bourne shell (C<sh(1)>) redirection syntax in
745backticks, not C<csh(1)>!  Details on why Perl's C<system()> and backtick
746and pipe opens all use the Bourne shell are in the
747F<versus/csh.whynot> article in the "Far More Than You Ever Wanted To
748Know" collection in L<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> . To
749capture a command's STDERR and STDOUT together:
750
751    $output = `cmd 2>&1`;                       # either with backticks
752    $pid = open(PH, "cmd 2>&1 |");              # or with an open pipe
753    while (<PH>) { }                            #    plus a read
754
755To capture a command's STDOUT but discard its STDERR:
756
757    $output = `cmd 2>/dev/null`;                # either with backticks
758    $pid = open(PH, "cmd 2>/dev/null |");       # or with an open pipe
759    while (<PH>) { }                            #    plus a read
760
761To capture a command's STDERR but discard its STDOUT:
762
763    $output = `cmd 2>&1 1>/dev/null`;           # either with backticks
764    $pid = open(PH, "cmd 2>&1 1>/dev/null |");  # or with an open pipe
765    while (<PH>) { }                            #    plus a read
766
767To exchange a command's STDOUT and STDERR in order to capture the STDERR
768but leave its STDOUT to come out our old STDERR:
769
770    $output = `cmd 3>&1 1>&2 2>&3 3>&-`;        # either with backticks
771    $pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
772    while (<PH>) { }                            #    plus a read
773
774To read both a command's STDOUT and its STDERR separately, it's easiest
775to redirect them separately to files, and then read from those files
776when the program is done:
777
778    system("program args 1>program.stdout 2>program.stderr");
779
780Ordering is important in all these examples. That's because the shell
781processes file descriptor redirections in strictly left to right order.
782
783    system("prog args 1>tmpfile 2>&1");
784    system("prog args 2>&1 1>tmpfile");
785
786The first command sends both standard out and standard error to the
787temporary file. The second command sends only the old standard output
788there, and the old standard error shows up on the old standard out.
789
790=head2 Why doesn't open() return an error when a pipe open fails?
791
792If the second argument to a piped C<open()> contains shell
793metacharacters, perl C<fork()>s, then C<exec()>s a shell to decode the
794metacharacters and eventually run the desired program. If the program
795couldn't be run, it's the shell that gets the message, not Perl. All
796your Perl program can find out is whether the shell itself could be
797successfully started. You can still capture the shell's STDERR and
798check it for error messages. See L<"How can I capture STDERR from an
799external command?"> elsewhere in this document, or use the
800L<IPC::Open3> module.
801
802If there are no shell metacharacters in the argument of C<open()>, Perl
803runs the command directly, without using the shell, and can correctly
804report whether the command started.
805
806=head2 What's wrong with using backticks in a void context?
807
808Strictly speaking, nothing. Stylistically speaking, it's not a good
809way to write maintainable code. Perl has several operators for
810running external commands. Backticks are one; they collect the output
811from the command for use in your program. The C<system> function is
812another; it doesn't do this.
813
814Writing backticks in your program sends a clear message to the readers
815of your code that you wanted to collect the output of the command.
816Why send a clear message that isn't true?
817
818Consider this line:
819
820    `cat /etc/termcap`;
821
822You forgot to check C<$?> to see whether the program even ran
823correctly. Even if you wrote
824
825    print `cat /etc/termcap`;
826
827this code could and probably should be written as
828
829    system("cat /etc/termcap") == 0
830    or die "cat program failed!";
831
832which will echo the cat command's output as it is generated, instead
833of waiting until the program has completed to print it out. It also
834checks the return value.
835
836C<system> also provides direct control over whether shell wildcard
837processing may take place, whereas backticks do not.
838
839=head2 How can I call backticks without shell processing?
840
841This is a bit tricky. You can't simply write the command
842like this:
843
844    @ok = `grep @opts '$search_string' @filenames`;
845
846As of Perl 5.8.0, you can use C<open()> with multiple arguments.
847Just like the list forms of C<system()> and C<exec()>, no shell
848escapes happen.
849
850    open( GREP, "-|", 'grep', @opts, $search_string, @filenames );
851    chomp(@ok = <GREP>);
852    close GREP;
853
854You can also:
855
856    my @ok = ();
857    if (open(GREP, "-|")) {
858        while (<GREP>) {
859            chomp;
860            push(@ok, $_);
861        }
862        close GREP;
863    } else {
864        exec 'grep', @opts, $search_string, @filenames;
865    }
866
867Just as with C<system()>, no shell escapes happen when you C<exec()> a
868list. Further examples of this can be found in L<perlipc/"Safe Pipe
869Opens">.
870
871Note that if you're using Windows, no solution to this vexing issue is
872even possible. Even though Perl emulates C<fork()>, you'll still be
873stuck, because Windows does not have an argc/argv-style API.
874
875=head2 Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?
876
877This happens only if your perl is compiled to use stdio instead of
878perlio, which is the default. Some (maybe all?) stdios set error and
879eof flags that you may need to clear. The L<POSIX> module defines
880C<clearerr()> that you can use. That is the technically correct way to
881do it. Here are some less reliable workarounds:
882
883=over 4
884
885=item 1
886
887Try keeping around the seekpointer and go there, like this:
888
889    my $where = tell($log_fh);
890    seek($log_fh, $where, 0);
891
892=item 2
893
894If that doesn't work, try seeking to a different part of the file and
895then back.
896
897=item 3
898
899If that doesn't work, try seeking to a different part of
900the file, reading something, and then seeking back.
901
902=item 4
903
904If that doesn't work, give up on your stdio package and use sysread.
905
906=back
907
908=head2 How can I convert my shell script to perl?
909
910Learn Perl and rewrite it. Seriously, there's no simple converter.
911Things that are awkward to do in the shell are easy to do in Perl, and
912this very awkwardness is what would make a shell->perl converter
913nigh-on impossible to write. By rewriting it, you'll think about what
914you're really trying to do, and hopefully will escape the shell's
915pipeline datastream paradigm, which while convenient for some matters,
916causes many inefficiencies.
917
918=head2 Can I use perl to run a telnet or ftp session?
919
920Try the L<Net::FTP>, L<TCP::Client>, and L<Net::Telnet> modules
921(available from CPAN).
922L<http://www.cpan.org/scripts/netstuff/telnet.emul.shar> will also help
923for emulating the telnet protocol, but L<Net::Telnet> is quite
924probably easier to use.
925
926If all you want to do is pretend to be telnet but don't need
927the initial telnet handshaking, then the standard dual-process
928approach will suffice:
929
930    use IO::Socket;             # new in 5.004
931    my $handle = IO::Socket::INET->new('www.perl.com:80')
932        or die "can't connect to port 80 on www.perl.com $!";
933    $handle->autoflush(1);
934    if (fork()) {               # XXX: undef means failure
935        select($handle);
936        print while <STDIN>;    # everything from stdin to socket
937    } else {
938        print while <$handle>;  # everything from socket to stdout
939    }
940    close $handle;
941    exit;
942
943=head2 How can I write expect in Perl?
944
945Once upon a time, there was a library called F<chat2.pl> (part of the
946standard perl distribution), which never really got finished. If you
947find it somewhere, I<don't use it>. These days, your best bet is to
948look at the L<Expect> module available from CPAN, which also requires two
949other modules from CPAN, L<IO::Pty> and L<IO::Stty>.
950
951=head2 Is there a way to hide perl's command line from programs such as "ps"?
952
953First of all note that if you're doing this for security reasons (to
954avoid people seeing passwords, for example) then you should rewrite
955your program so that critical information is never given as an
956argument. Hiding the arguments won't make your program completely
957secure.
958
959To actually alter the visible command line, you can assign to the
960variable $0 as documented in L<perlvar>. This won't work on all
961operating systems, though. Daemon programs like sendmail place their
962state there, as in:
963
964    $0 = "orcus [accepting connections]";
965
966=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?
967
968=over 4
969
970=item Unix
971
972In the strictest sense, it can't be done--the script executes as a
973different process from the shell it was started from. Changes to a
974process are not reflected in its parent--only in any children
975created after the change. There is shell magic that may allow you to
976fake it by C<eval()>ing the script's output in your shell; check out the
977comp.unix.questions FAQ for details.
978
979=back
980
981=head2 How do I close a process's filehandle without waiting for it to complete?
982
983Assuming your system supports such things, just send an appropriate signal
984to the process (see L<perlfunc/"kill">). It's common to first send a TERM
985signal, wait a little bit, and then send a KILL signal to finish it off.
986
987=head2 How do I fork a daemon process?
988
989If by daemon process you mean one that's detached (disassociated from
990its tty), then the following process is reported to work on most
991Unixish systems. Non-Unix users should check their Your_OS::Process
992module for other solutions.
993
994=over 4
995
996=item *
997
998Open /dev/tty and use the TIOCNOTTY ioctl on it. See L<tty(1)>
999for details. Or better yet, you can just use the C<POSIX::setsid()>
1000function, so you don't have to worry about process groups.
1001
1002=item *
1003
1004Change directory to /
1005
1006=item *
1007
1008Reopen STDIN, STDOUT, and STDERR so they're not connected to the old
1009tty.
1010
1011=item *
1012
1013Background yourself like this:
1014
1015    fork && exit;
1016
1017=back
1018
1019The L<Proc::Daemon> module, available from CPAN, provides a function to
1020perform these actions for you.
1021
1022=head2 How do I find out if I'm running interactively or not?
1023
1024(contributed by brian d foy)
1025
1026This is a difficult question to answer, and the best answer is
1027only a guess.
1028
1029What do you really want to know? If you merely want to know if one of
1030your filehandles is connected to a terminal, you can try the C<-t>
1031file test:
1032
1033    if( -t STDOUT ) {
1034        print "I'm connected to a terminal!\n";
1035    }
1036
1037However, you might be out of luck if you expect that means there is a
1038real person on the other side. With the L<Expect> module, another
1039program can pretend to be a person. The program might even come close
1040to passing the Turing test.
1041
1042The L<IO::Interactive> module does the best it can to give you an
1043answer. Its C<is_interactive> function returns an output filehandle;
1044that filehandle points to standard output if the module thinks the
1045session is interactive. Otherwise, the filehandle is a null handle
1046that simply discards the output:
1047
1048    use IO::Interactive;
1049
1050    print { is_interactive } "I might go to standard output!\n";
1051
1052This still doesn't guarantee that a real person is answering your
1053prompts or reading your output.
1054
1055If you want to know how to handle automated testing for your
1056distribution, you can check the environment. The CPAN
1057Testers, for instance, set the value of C<AUTOMATED_TESTING>:
1058
1059    unless( $ENV{AUTOMATED_TESTING} ) {
1060        print "Hello interactive tester!\n";
1061    }
1062
1063=head2 How do I timeout a slow event?
1064
1065Use the C<alarm()> function, probably in conjunction with a signal
1066handler, as documented in L<perlipc/"Signals"> and the section on
1067"Signals" in the Camel. You may instead use the more flexible
1068L<Sys::AlarmCall> module available from CPAN.
1069
1070The C<alarm()> function is not implemented on all versions of Windows.
1071Check the documentation for your specific version of Perl.
1072
1073=head2 How do I set CPU limits?
1074X<BSD::Resource> X<limit> X<CPU>
1075
1076(contributed by Xho)
1077
1078Use the L<BSD::Resource> module from CPAN. As an example:
1079
1080    use BSD::Resource;
1081    setrlimit(RLIMIT_CPU,10,20) or die $!;
1082
1083This sets the soft and hard limits to 10 and 20 seconds, respectively.
1084After 10 seconds of time spent running on the CPU (not "wall" time),
1085the process will be sent a signal (XCPU on some systems) which, if not
1086trapped, will cause the process to terminate. If that signal is
1087trapped, then after 10 more seconds (20 seconds in total) the process
1088will be killed with a non-trappable signal.
1089
1090See the L<BSD::Resource> and your systems documentation for the gory
1091details.
1092
1093=head2 How do I avoid zombies on a Unix system?
1094
1095Use the reaper code from L<perlipc/"Signals"> to call C<wait()> when a
1096SIGCHLD is received, or else use the double-fork technique described
1097in L<perlfaq8/"How do I start a process in the background?">.
1098
1099=head2 How do I use an SQL database?
1100
1101The L<DBI> module provides an abstract interface to most database
1102servers and types, including Oracle, DB2, Sybase, mysql, Postgresql,
1103ODBC, and flat files. The DBI module accesses each database type
1104through a database driver, or DBD. You can see a complete list of
1105available drivers on CPAN: L<http://www.cpan.org/modules/by-module/DBD/> .
1106You can read more about DBI on L<http://dbi.perl.org/> .
1107
1108Other modules provide more specific access: L<Win32::ODBC>, L<Alzabo>,
1109C<iodbc>, and others found on CPAN Search: L<https://metacpan.org/> .
1110
1111=head2 How do I make a system() exit on control-C?
1112
1113You can't. You need to imitate the C<system()> call (see L<perlipc> for
1114sample code) and then have a signal handler for the INT signal that
1115passes the signal on to the subprocess. Or you can check for it:
1116
1117    $rc = system($cmd);
1118    if ($rc & 127) { die "signal death" }
1119
1120=head2 How do I open a file without blocking?
1121
1122If you're lucky enough to be using a system that supports
1123non-blocking reads (most Unixish systems do), you need only to use the
1124C<O_NDELAY> or C<O_NONBLOCK> flag from the C<Fcntl> module in conjunction with
1125C<sysopen()>:
1126
1127    use Fcntl;
1128    sysopen(my $fh, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)
1129        or die "can't open /foo/somefile: $!":
1130
1131=head2 How do I tell the difference between errors from the shell and perl?
1132
1133(answer contributed by brian d foy)
1134
1135When you run a Perl script, something else is running the script for you,
1136and that something else may output error messages. The script might
1137emit its own warnings and error messages. Most of the time you cannot
1138tell who said what.
1139
1140You probably cannot fix the thing that runs perl, but you can change how
1141perl outputs its warnings by defining a custom warning and die functions.
1142
1143Consider this script, which has an error you may not notice immediately.
1144
1145    #!/usr/locl/bin/perl
1146
1147    print "Hello World\n";
1148
1149I get an error when I run this from my shell (which happens to be
1150bash). That may look like perl forgot it has a C<print()> function,
1151but my shebang line is not the path to perl, so the shell runs the
1152script, and I get the error.
1153
1154    $ ./test
1155    ./test: line 3: print: command not found
1156
1157A quick and dirty fix involves a little bit of code, but this may be all
1158you need to figure out the problem.
1159
1160    #!/usr/bin/perl -w
1161
1162    BEGIN {
1163        $SIG{__WARN__} = sub{ print STDERR "Perl: ", @_; };
1164        $SIG{__DIE__}  = sub{ print STDERR "Perl: ", @_; exit 1};
1165    }
1166
1167    $a = 1 + undef;
1168    $x / 0;
1169    __END__
1170
1171The perl message comes out with "Perl" in front. The C<BEGIN> block
1172works at compile time so all of the compilation errors and warnings
1173get the "Perl:" prefix too.
1174
1175    Perl: Useless use of division (/) in void context at ./test line 9.
1176    Perl: Name "main::a" used only once: possible typo at ./test line 8.
1177    Perl: Name "main::x" used only once: possible typo at ./test line 9.
1178    Perl: Use of uninitialized value in addition (+) at ./test line 8.
1179    Perl: Use of uninitialized value in division (/) at ./test line 9.
1180    Perl: Illegal division by zero at ./test line 9.
1181    Perl: Illegal division by zero at -e line 3.
1182
1183If I don't see that "Perl:", it's not from perl.
1184
1185You could also just know all the perl errors, and although there are
1186some people who may know all of them, you probably don't. However, they
1187all should be in the L<perldiag> manpage. If you don't find the error in
1188there, it probably isn't a perl error.
1189
1190Looking up every message is not the easiest way, so let perl to do it
1191for you. Use the diagnostics pragma with turns perl's normal messages
1192into longer discussions on the topic.
1193
1194    use diagnostics;
1195
1196If you don't get a paragraph or two of expanded discussion, it
1197might not be perl's message.
1198
1199=head2 How do I install a module from CPAN?
1200
1201(contributed by brian d foy)
1202
1203The easiest way is to have a module also named CPAN do it for you by using
1204the C<cpan> command that comes with Perl. You can give it a list of modules
1205to install:
1206
1207    $ cpan IO::Interactive Getopt::Whatever
1208
1209If you prefer C<CPANPLUS>, it's just as easy:
1210
1211    $ cpanp i IO::Interactive Getopt::Whatever
1212
1213If you want to install a distribution from the current directory, you can
1214tell C<CPAN.pm> to install C<.> (the full stop):
1215
1216    $ cpan .
1217
1218See the documentation for either of those commands to see what else
1219you can do.
1220
1221If you want to try to install a distribution by yourself, resolving
1222all dependencies on your own, you follow one of two possible build
1223paths.
1224
1225For distributions that use I<Makefile.PL>:
1226
1227    $ perl Makefile.PL
1228    $ make test install
1229
1230For distributions that use I<Build.PL>:
1231
1232    $ perl Build.PL
1233    $ ./Build test
1234    $ ./Build install
1235
1236Some distributions may need to link to libraries or other third-party
1237code and their build and installation sequences may be more complicated.
1238Check any I<README> or I<INSTALL> files that you may find.
1239
1240=head2 What's the difference between require and use?
1241
1242(contributed by brian d foy)
1243
1244Perl runs C<require> statement at run-time. Once Perl loads, compiles,
1245and runs the file, it doesn't do anything else. The C<use> statement
1246is the same as a C<require> run at compile-time, but Perl also calls the
1247C<import> method for the loaded package. These two are the same:
1248
1249    use MODULE qw(import list);
1250
1251    BEGIN {
1252        require MODULE;
1253        MODULE->import(import list);
1254    }
1255
1256However, you can suppress the C<import> by using an explicit, empty
1257import list. Both of these still happen at compile-time:
1258
1259    use MODULE ();
1260
1261    BEGIN {
1262        require MODULE;
1263    }
1264
1265Since C<use> will also call the C<import> method, the actual value
1266for C<MODULE> must be a bareword. That is, C<use> cannot load files
1267by name, although C<require> can:
1268
1269    require "$ENV{HOME}/lib/Foo.pm"; # no @INC searching!
1270
1271See the entry for C<use> in L<perlfunc> for more details.
1272
1273=head2 How do I keep my own module/library directory?
1274
1275When you build modules, tell Perl where to install the modules.
1276
1277If you want to install modules for your own use, the easiest way might
1278be L<local::lib>, which you can download from CPAN. It sets various
1279installation settings for you, and uses those same settings within
1280your programs.
1281
1282If you want more flexibility, you need to configure your CPAN client
1283for your particular situation.
1284
1285For C<Makefile.PL>-based distributions, use the INSTALL_BASE option
1286when generating Makefiles:
1287
1288    perl Makefile.PL INSTALL_BASE=/mydir/perl
1289
1290You can set this in your C<CPAN.pm> configuration so modules
1291automatically install in your private library directory when you use
1292the CPAN.pm shell:
1293
1294    % cpan
1295    cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
1296    cpan> o conf commit
1297
1298For C<Build.PL>-based distributions, use the --install_base option:
1299
1300    perl Build.PL --install_base /mydir/perl
1301
1302You can configure C<CPAN.pm> to automatically use this option too:
1303
1304    % cpan
1305    cpan> o conf mbuild_arg "--install_base /mydir/perl"
1306    cpan> o conf commit
1307
1308INSTALL_BASE tells these tools to put your modules into
1309F</mydir/perl/lib/perl5>. See L<How do I add a directory to my
1310include path (@INC) at runtime?> for details on how to run your newly
1311installed modules.
1312
1313There is one caveat with INSTALL_BASE, though, since it acts
1314differently from the PREFIX and LIB settings that older versions of
1315L<ExtUtils::MakeMaker> advocated. INSTALL_BASE does not support
1316installing modules for multiple versions of Perl or different
1317architectures under the same directory. You should consider whether you
1318really want that and, if you do, use the older PREFIX and LIB
1319settings. See the L<ExtUtils::Makemaker> documentation for more details.
1320
1321=head2 How do I add the directory my program lives in to the module/library search path?
1322
1323(contributed by brian d foy)
1324
1325If you know the directory already, you can add it to C<@INC> as you would
1326for any other directory. You might <use lib> if you know the directory
1327at compile time:
1328
1329    use lib $directory;
1330
1331The trick in this task is to find the directory. Before your script does
1332anything else (such as a C<chdir>), you can get the current working
1333directory with the C<Cwd> module, which comes with Perl:
1334
1335    BEGIN {
1336        use Cwd;
1337        our $directory = cwd;
1338    }
1339
1340    use lib $directory;
1341
1342You can do a similar thing with the value of C<$0>, which holds the
1343script name. That might hold a relative path, but C<rel2abs> can turn
1344it into an absolute path. Once you have the
1345
1346    BEGIN {
1347        use File::Spec::Functions qw(rel2abs);
1348        use File::Basename qw(dirname);
1349
1350        my $path   = rel2abs( $0 );
1351        our $directory = dirname( $path );
1352    }
1353
1354    use lib $directory;
1355
1356The L<FindBin> module, which comes with Perl, might work. It finds the
1357directory of the currently running script and puts it in C<$Bin>, which
1358you can then use to construct the right library path:
1359
1360    use FindBin qw($Bin);
1361
1362You can also use L<local::lib> to do much of the same thing. Install
1363modules using L<local::lib>'s settings then use the module in your
1364program:
1365
1366     use local::lib; # sets up a local lib at ~/perl5
1367
1368See the L<local::lib> documentation for more details.
1369
1370=head2 How do I add a directory to my include path (@INC) at runtime?
1371
1372Here are the suggested ways of modifying your include path, including
1373environment variables, run-time switches, and in-code statements:
1374
1375=over 4
1376
1377=item the C<PERLLIB> environment variable
1378
1379    $ export PERLLIB=/path/to/my/dir
1380    $ perl program.pl
1381
1382=item the C<PERL5LIB> environment variable
1383
1384    $ export PERL5LIB=/path/to/my/dir
1385    $ perl program.pl
1386
1387=item the C<perl -Idir> command line flag
1388
1389    $ perl -I/path/to/my/dir program.pl
1390
1391=item the C<lib> pragma:
1392
1393    use lib "$ENV{HOME}/myown_perllib";
1394
1395=item the L<local::lib> module:
1396
1397    use local::lib;
1398
1399    use local::lib "~/myown_perllib";
1400
1401=back
1402
1403The last is particularly useful because it knows about machine-dependent
1404architectures. The C<lib.pm> pragmatic module was first
1405included with the 5.002 release of Perl.
1406
1407=head2 Where are modules installed?
1408
1409Modules are installed on a case-by-case basis (as provided by the methods
1410described in the previous section), and in the operating system. All of these
1411paths are stored in @INC, which you can display with the one-liner
1412
1413    perl -e 'print join("\n",@INC,"")'
1414
1415The same information is displayed at the end of the output from the command
1416
1417    perl -V
1418
1419To find out where a module's source code is located, use
1420
1421    perldoc -l Encode
1422
1423to display the path to the module. In some cases (for example, the C<AutoLoader>
1424module), this command will show the path to a separate C<pod> file; the module
1425itself should be in the same directory, with a 'pm' file extension.
1426
1427=head2 What is socket.ph and where do I get it?
1428
1429It's a Perl 4 style file defining values for system networking
1430constants. Sometimes it is built using L<h2ph> when Perl is installed,
1431but other times it is not. Modern programs should use C<use Socket;>
1432instead.
1433
1434=head1 AUTHOR AND COPYRIGHT
1435
1436Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and
1437other authors as noted. All rights reserved.
1438
1439This documentation is free; you can redistribute it and/or modify it
1440under the same terms as Perl itself.
1441
1442Irrespective of its distribution, all code examples in this file
1443are hereby placed into the public domain. You are permitted and
1444encouraged to use this code in your own programs for fun
1445or for profit as you see fit. A simple comment in the code giving
1446credit would be courteous but is not required.
1447