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