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