[PATCH] perlcommunity.pod: add information about OSDC.fr
[p5sagit/p5-mst-13.2.git] / pod / perlfaq8.pod
index 89f5b51..9530524 100644 (file)
@@ -1,6 +1,6 @@
 =head1 NAME
 
-perlfaq8 - System Interaction ($Revision: 6628 $)
+perlfaq8 - System Interaction
 
 =head1 DESCRIPTION
 
@@ -20,11 +20,16 @@ the name of the operating system (not its release number) that your perl
 binary was built for.
 
 =head2 How come exec() doesn't return?
+X<exec> X<system> X<fork> X<open> X<pipe>
 
-Because that's what it does: it replaces your currently running
-program with a different one.  If you want to keep going (as is
-probably the case if you're asking this question) use system()
-instead.
+(contributed by brian d foy)
+
+The C<exec> function's job is to turn your process into another
+command and never to return. If that's not what you want to do, don't
+use C<exec>. :)
+
+If you want to run an external command and still keep your Perl process
+going, look at a piped C<open>, C<fork>, or C<system>.
 
 =head2 How do I do fancy stuff with the keyboard/screen/mouse?
 
@@ -169,24 +174,50 @@ not to block:
 
 =head2 How do I clear the screen?
 
-If you only have do so infrequently, use C<system>:
+(contributed by brian d foy)
 
-       system("clear");
+To clear the screen, you just have to print the special sequence
+that tells the terminal to clear the screen. Once you have that
+sequence, output it when you want to clear the screen.
 
-If you have to do this a lot, save the clear string
-so you can print it 100 times without calling a program
-100 times:
+You can use the C<Term::ANSIScreen> module to get the special
+sequence. Import the C<cls> function (or the C<:screen> tag):
 
-       $clear_string = `clear`;
-       print $clear_string;
+       use Term::ANSIScreen qw(cls);
+       my $clear_screen = cls();
+
+       print $clear_screen;
 
-If you're planning on doing other screen manipulations, like cursor
-positions, etc, you might wish to use Term::Cap module:
+The C<Term::Cap> module can also get the special sequence if you want
+to deal with the low-level details of terminal control. The C<Tputs>
+method returns the string for the given capability:
 
        use Term::Cap;
-       $terminal = Term::Cap->Tgetent( {OSPEED => 9600} );
+
+       $terminal = Term::Cap->Tgetent( { OSPEED => 9600 } );
        $clear_string = $terminal->Tputs('cl');
 
+       print $clear_screen;
+
+On Windows, you can use the C<Win32::Console> module. After creating
+an object for the output filehandle you want to affect, call the
+C<Cls> method:
+
+       Win32::Console;
+
+       $OUT = Win32::Console->new(STD_OUTPUT_HANDLE);
+       my $clear_string = $OUT->Cls;
+
+       print $clear_screen;
+
+If you have a command-line program that does the job, you can call
+it in backticks to capture whatever it outputs so you can use it
+later:
+
+       $clear_string = `clear`;
+
+       print $clear_string;
+
 =head2 How do I get the screen size?
 
 If you have Term::ReadKey module installed from CPAN,
@@ -334,12 +365,11 @@ You spend lots and lots of money on dedicated hardware, but this is
 bound to get you talked about.
 
 Seriously, you can't if they are Unix password files--the Unix
-password system employs one-way encryption.  It's more like hashing than
-encryption.  The best you can check is whether something else hashes to
-the same string.  You can't turn a hash back into the original string.
-Programs like Crack
-can forcibly (and intelligently) try to guess passwords, but don't
-(can't) guarantee quick success.
+password system employs one-way encryption.  It's more like hashing
+than encryption.  The best you can do is check whether something else
+hashes to the same string.  You can't turn a hash back into the
+original string. Programs like Crack can forcibly (and intelligently)
+try to guess passwords, but don't (can't) guarantee quick success.
 
 If you're worried about users selecting bad passwords, you should
 proactively check when they try to change their password (by modifying
@@ -347,18 +377,25 @@ passwd(1), for example).
 
 =head2 How do I start a process in the background?
 
-Several modules can start other processes that do not block
-your Perl program.  You can use IPC::Open3, Parallel::Jobs,
-IPC::Run, and some of the POE modules.  See CPAN for more
-details.
+(contributed by brian d foy)
+
+There's not a single way to run code in the background so you don't
+have to wait for it to finish before your program moves on to other
+tasks. Process management depends on your particular operating system,
+and many of the techniques are in L<perlipc>.
+
+Several CPAN modules may be able to help, including IPC::Open2 or
+IPC::Open3, IPC::Run, Parallel::Jobs, Parallel::ForkManager, POE,
+Proc::Background, and Win32::Process. There are many other modules you
+might use, so check those namespaces for other options too.
 
-You could also use
+If you are on a unix-like system, you might be able to get away with a
+system call where you put an C<&> on the end of the command:
 
        system("cmd &")
 
-or you could use fork as documented in L<perlfunc/"fork">, with
-further examples in L<perlipc>.  Some things to be aware of, if you're
-on a Unix-like system:
+You can also try using C<fork>, as described in L<perlfunc> (although
+this is the same thing that many of the modules will do for you).
 
 =over 4
 
@@ -462,48 +499,25 @@ probably get away with setting an environment variable:
        system "trn comp.lang.perl.misc";
 
 =head2 How can I sleep() or alarm() for under a second?
+X<Time::HiRes> X<BSD::Itimer> X<sleep> X<select>
 
-If you want finer granularity than the 1 second that the sleep()
-function provides, the easiest way is to use the select() function as
-documented in L<perlfunc/"select">.  Try the Time::HiRes and
-the BSD::Itimer modules (available from CPAN, and starting from
-Perl 5.8 Time::HiRes is part of the standard distribution).
+If you want finer granularity than the 1 second that the C<sleep()>
+function provides, the easiest way is to use the C<select()> function as
+documented in L<perlfunc/"select">.  Try the C<Time::HiRes> and
+the C<BSD::Itimer> modules (available from CPAN, and starting from
+Perl 5.8 C<Time::HiRes> is part of the standard distribution).
 
 =head2 How can I measure time under a second?
+X<Time::HiRes> X<BSD::Itimer> X<sleep> X<select>
 
-In general, you may not be able to.  The Time::HiRes module (available
-from CPAN, and starting from Perl 5.8 part of the standard distribution)
-provides this functionality for some systems.
+(contributed by brian d foy)
 
-If your system supports both the syscall() function in Perl as well as
-a system call like gettimeofday(2), then you may be able to do
-something like this:
-
-       require 'sys/syscall.ph';
-
-       $TIMEVAL_T = "LL";
-
-       $done = $start = pack($TIMEVAL_T, ());
-
-       syscall(&SYS_gettimeofday, $start, 0) != -1
-               or die "gettimeofday: $!";
-
-          ##########################
-          # DO YOUR OPERATION HERE #
-          ##########################
-
-       syscall( &SYS_gettimeofday, $done, 0) != -1
-               or die "gettimeofday: $!";
-
-       @start = unpack($TIMEVAL_T, $start);
-       @done  = unpack($TIMEVAL_T, $done);
-
-       # fix microseconds
-       for ($done[1], $start[1]) { $_ /= 1_000_000 }
-
-       $delta_time = sprintf "%.4f", ($done[0]  + $done[1]  )
-                                                                                       -
-                                                                ($start[0] + $start[1] );
+The C<Time::HiRes> module (part of the standard distribution as of
+Perl 5.8) measures time with the C<gettimeofday()> system call, which
+returns the time in microseconds since the epoch. If you can't install
+C<Time::HiRes> for older Perls and you are on a Unixish system, you
+may be able to call C<gettimeofday(2)> directly. See
+L<perlfunc/syscall>.
 
 =head2 How can I do an atexit() or setjmp()/longjmp()? (Exception handling)
 
@@ -804,8 +818,9 @@ this code could and probably should be written as
        system("cat /etc/termcap") == 0
        or die "cat program failed!";
 
-which will get the output quickly (as it is generated, instead of only
-at the end) and also check the return value.
+which will echo the cat command's output as it is generated, instead
+of waiting until the program has completed to print it out. It also
+checks the return value.
 
 C<system> also provides direct control over whether shell wildcard
 processing may take place, whereas backticks do not.
@@ -817,8 +832,8 @@ like this:
 
        @ok = `grep @opts '$search_string' @filenames`;
 
-As of Perl 5.8.0, you can use open() with multiple arguments.
-Just like the list forms of system() and exec(), no shell
+As of Perl 5.8.0, you can use C<open()> with multiple arguments.
+Just like the list forms of C<system()> and C<exec()>, no shell
 escapes happen.
 
        open( GREP, "-|", 'grep', @opts, $search_string, @filenames );
@@ -832,25 +847,27 @@ You can also:
                while (<GREP>) {
                        chomp;
                        push(@ok, $_);
-           }
-           close GREP;
+               }
+               close GREP;
        } else {
                exec 'grep', @opts, $search_string, @filenames;
        }
 
-Just as with system(), no shell escapes happen when you exec() a list.
-Further examples of this can be found in L<perlipc/"Safe Pipe Opens">.
+Just as with C<system()>, no shell escapes happen when you C<exec()> a
+list. Further examples of this can be found in L<perlipc/"Safe Pipe
+Opens">.
 
-Note that if you're use Microsoft, no solution to this vexing issue
-is even possible.  Even if Perl were to emulate fork(), you'd still
-be stuck, because Microsoft does not have a argc/argv-style API.
+Note that if you're using Windows, no solution to this vexing issue is
+even possible.  Even if Perl were to emulate C<fork()>, you'd still be
+stuck, because Windows does not have an argc/argv-style API.
 
 =head2 Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?
 
-Some stdio's set error and eof flags that need clearing.  The
-POSIX module defines clearerr() that you can use.  That is the
-technically correct way to do it.  Here are some less reliable
-workarounds:
+This happens only if your perl is compiled to use stdio instead of
+perlio, which is the default. Some (maybe all?) stdio's set error and
+eof flags that you may need to clear. The POSIX module defines
+clearerr() that you can use.  That is the technically correct way to
+do it.  Here are some less reliable workarounds:
 
 =over 4
 
@@ -1029,8 +1046,24 @@ The alarm() function is not implemented on all versions of Windows.
 Check the documentation for your specific version of Perl.
 
 =head2 How do I set CPU limits?
+X<BSD::Resource> X<limit> X<CPU>
+
+(contributed by Xho)
+
+Use the C<BSD::Resource> module from CPAN. As an example:
 
-Use the BSD::Resource module from CPAN.
+       use BSD::Resource;
+       setrlimit(RLIMIT_CPU,10,20) or die $!;
+
+This sets the soft and hard limits to 10 and 20 seconds, respectively.
+After 10 seconds of time spent running on the CPU (not "wall" time),
+the process will be sent a signal (XCPU on some systems) which, if not
+trapped, will cause the process to terminate.  If that signal is
+trapped, then after 10 more seconds (20 seconds in total) the process
+will be killed with a non-trappable signal.
+
+See the C<BSD::Resource> and your systems documentation for the gory
+details.
 
 =head2 How do I avoid zombies on a Unix system?
 
@@ -1072,7 +1105,7 @@ sysopen():
 
 =head2 How do I tell the difference between errors from the shell and perl?
 
-(answer contributed by brian d foy, C<< <bdfoy@cpan.org> >>
+(answer contributed by brian d foy)
 
 When you run a Perl script, something else is running the script for you,
 and that something else may output error messages.  The script might
@@ -1187,85 +1220,165 @@ and use?".
 
 =head2 What's the difference between require and use?
 
-Perl offers several different ways to include code from one file into
-another.  Here are the deltas between the various inclusion constructs:
+(contributed by brian d foy)
 
-       1)  do $file is like eval `cat $file`, except the former
-       1.1: searches @INC and updates %INC.
-       1.2: bequeaths an *unrelated* lexical scope on the eval'ed code.
+Perl runs C<require> statement at run-time. Once Perl loads, compiles,
+and runs the file, it doesn't do anything else. The C<use> statement
+is the same as a C<require> run at compile-time, but Perl also calls the
+C<import> method for the loaded package. These two are the same:
 
-       2)  require $file is like do $file, except the former
-       2.1: checks for redundant loading, skipping already loaded files.
-       2.2: raises an exception on failure to find, compile, or execute $file.
+       use MODULE qw(import list);
 
-       3)  require Module is like require "Module.pm", except the former
-       3.1: translates each "::" into your system's directory separator.
-       3.2: primes the parser to disambiguate class Module as an indirect object.
+       BEGIN {
+               require MODULE;
+               MODULE->import(import list);
+               }
 
-       4)  use Module is like require Module, except the former
-       4.1: loads the module at compile time, not run-time.
-       4.2: imports symbols and semantics from that package to the current one.
+However, you can suppress the C<import> by using an explicit, empty
+import list. Both of these still happen at compile-time:
 
-In general, you usually want C<use> and a proper Perl module.
+       use MODULE ();
+
+       BEGIN {
+               require MODULE;
+               }
+
+Since C<use> will also call the C<import> method, the actual value
+for C<MODULE> must be a bareword. That is, C<use> cannot load files
+by name, although C<require> can:
+
+       require "$ENV{HOME}/lib/Foo.pm"; # no @INC searching!
+
+See the entry for C<use> in L<perlfunc> for more details.
 
 =head2 How do I keep my own module/library directory?
 
-When you build modules, use the PREFIX and LIB options when generating
-Makefiles:
+When you build modules, tell Perl where to install the modules.
 
-       perl Makefile.PL PREFIX=/mydir/perl LIB=/mydir/perl/lib
+For C<Makefile.PL>-based distributions, use the INSTALL_BASE option
+when generating Makefiles:
 
-then either set the PERL5LIB environment variable before you run
-scripts that use the modules/libraries (see L<perlrun>) or say
+       perl Makefile.PL INSTALL_BASE=/mydir/perl
 
-       use lib '/mydir/perl/lib';
+You can set this in your CPAN.pm configuration so modules automatically install
+in your private library directory when you use the CPAN.pm shell:
 
-This is almost the same as
+       % cpan
+       cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
+       cpan> o conf commit
 
-       BEGIN {
-       unshift(@INC, '/mydir/perl/lib');
-       }
+For C<Build.PL>-based distributions, use the --install_base option:
+
+       perl Build.PL --install_base /mydir/perl
+
+You can configure CPAN.pm to automatically use this option too:
+
+       % cpan
+       cpan> o conf mbuild_arg --install_base /mydir/perl
+       cpan> o conf commit
 
-except that the lib module checks for machine-dependent subdirectories.
-See Perl's L<lib> for more information.
+INSTALL_BASE tells these tools to put your modules into
+F</mydir/perl/lib/perl5>.  See L<How do I add a directory to my
+include path (@INC) at runtime?> for details on how to run your newly
+installed moudles.
+
+There is one caveat with INSTALL_BASE, though, since it acts
+differently than the PREFIX and LIB settings that older versions of
+ExtUtils::MakeMaker advocated. INSTALL_BASE does not support
+installing modules for multiple versions of Perl or different
+architectures under the same directory. You should consider if you
+really want that , and if you do, use the older PREFIX and LIB
+settings. See the ExtUtils::Makemaker documentation for more details.
 
 =head2 How do I add the directory my program lives in to the module/library search path?
 
-       use FindBin;
-       use lib "$FindBin::Bin";
-       use your_own_modules;
+(contributed by brian d foy)
+
+If you know the directory already, you can add it to C<@INC> as you would
+for any other directory. You might <use lib> if you know the directory
+at compile time:
+
+       use lib $directory;
+
+The trick in this task is to find the directory. Before your script does
+anything else (such as a C<chdir>), you can get the current working
+directory with the C<Cwd> module, which comes with Perl:
+
+       BEGIN {
+               use Cwd;
+               our $directory = cwd;
+               }
+
+       use lib $directory;
+
+You can do a similar thing with the value of C<$0>, which holds the
+script name. That might hold a relative path, but C<rel2abs> can turn
+it into an absolute path. Once you have the
+
+       BEGIN {
+               use File::Spec::Functions qw(rel2abs);
+               use File::Basename qw(dirname);
+
+               my $path   = rel2abs( $0 );
+               our $directory = dirname( $path );
+               }
+
+       use lib $directory;
+
+The C<FindBin> module, which comes with Perl, might work. It finds the
+directory of the currently running script and puts it in C<$Bin>, which
+you can then use to construct the right library path:
+
+       use FindBin qw($Bin);
 
 =head2 How do I add a directory to my include path (@INC) at runtime?
 
-Here are the suggested ways of modifying your include path:
+Here are the suggested ways of modifying your include path, including
+environment variables, run-time switches, and in-code statements:
+
+=over 4
+
+=item the PERLLIB environment variable
+
+       $ export PERLLIB=/path/to/my/dir
+       $ perl program.pl
+
+=item the PERL5LIB environment variable
+
+       $ export PERL5LIB=/path/to/my/dir
+       $ perl program.pl
+
+=item the perl -Idir command line flag
 
-       the PERLLIB environment variable
-       the PERL5LIB environment variable
-       the perl -Idir command line flag
-       the use lib pragma, as in
-               use lib "$ENV{HOME}/myown_perllib";
+       $ perl -I/path/to/my/dir program.pl
+
+=item the use lib pragma:
+
+       use lib "$ENV{HOME}/myown_perllib";
+
+=back
 
-The latter is particularly useful because it knows about machine
+The last is particularly useful because it knows about machine
 dependent architectures.  The lib.pm pragmatic module was first
 included with the 5.002 release of Perl.
 
 =head2 What is socket.ph and where do I get it?
 
-It's a perl4-style file defining values for system networking
+It's a Perl 4 style file defining values for system networking
 constants.  Sometimes it is built using h2ph when Perl is installed,
 but other times it is not.  Modern programs C<use Socket;> instead.
 
 =head1 REVISION
 
-Revision: $Revision: 6628 $
+Revision: $Revision$
 
-Date: $Date: 2006-07-09 14:46:14 +0200 (dim, 09 jui 2006) $
+Date: $Date$
 
 See L<perlfaq> for source control details and availability.
 
 =head1 AUTHOR AND COPYRIGHT
 
-Copyright (c) 1997-2006 Tom Christiansen, Nathan Torkington, and
+Copyright (c) 1997-2009 Tom Christiansen, Nathan Torkington, and
 other authors as noted. All rights reserved.
 
 This documentation is free; you can redistribute it and/or modify it