diff options
-rw-r--r-- | pod/perlfaq.pod | 6 | ||||
-rw-r--r-- | pod/perlfaq2.pod | 46 | ||||
-rw-r--r-- | pod/perlfaq3.pod | 218 | ||||
-rw-r--r-- | pod/perlfaq4.pod | 145 | ||||
-rw-r--r-- | pod/perlfaq6.pod | 12 | ||||
-rw-r--r-- | pod/perlfaq7.pod | 4 | ||||
-rw-r--r-- | pod/perlfaq8.pod | 2 | ||||
-rw-r--r-- | pod/perlfaq9.pod | 2 |
8 files changed, 252 insertions, 183 deletions
diff --git a/pod/perlfaq.pod b/pod/perlfaq.pod index a7f6ab835f..1d81077760 100644 --- a/pod/perlfaq.pod +++ b/pod/perlfaq.pod @@ -1,6 +1,6 @@ =head1 NAME -perlfaq - frequently asked questions about Perl ($Date: 1998/06/22 15:15:57 $) +perlfaq - frequently asked questions about Perl ($Date: 1998/07/20 23:12:17 $) =head1 DESCRIPTION @@ -18,7 +18,7 @@ Very general, high-level information about Perl. =item L<perlfaq2>: Obtaining and Learning about Perl -Where to find source and documentation to Perl, support and training, +Where to find source and documentation to Perl, support, and related matters. =item L<perlfaq3>: Programming Tools @@ -117,7 +117,7 @@ in respect of this information or its use. =over 4 -=item 22/June/98 +=head 22/June/98 Significant changes throughout in preparation for the 5.005 release. diff --git a/pod/perlfaq2.pod b/pod/perlfaq2.pod index a994042fef..c743a0efc8 100644 --- a/pod/perlfaq2.pod +++ b/pod/perlfaq2.pod @@ -1,11 +1,11 @@ =head1 NAME -perlfaq2 - Obtaining and Learning about Perl ($Revision: 1.20 $, $Date: 1998/07/05 15:07:20 $) +perlfaq2 - Obtaining and Learning about Perl ($Revision: 1.24 $, $Date: 1998/07/20 23:40:28 $) =head1 DESCRIPTION This section of the FAQ answers questions about where to find -source and documentation for Perl, support and training, and +source and documentation for Perl, support, and related matters. =head2 What machines support Perl? Where do I get it? @@ -15,22 +15,21 @@ development team) is distributed only in source code form. You can find this at http://www.perl.com/CPAN/src/latest.tar.gz, which is a gzipped archive in POSIX tar format. This source builds with no porting whatsoever on most Unix systems (Perl's native environment), -as well as Windows NT, Plan 9, VMS, QNX, OS/2, and the Amiga. - -Binary distributions for various platforms can be found -http://www.perl.com/CPAN/ports/ directory. Some of these ports (especially -the ones not part of the standard sources) may behave differently -than what is documented in the standard source documentation. These -differences can be either positive (e.g. extensions for the features of the -particular platform that are not supported in the source release of perl) -or negative (e.g. might be based upon a less current source release of perl). - -A useful FAQ for Win32 Perl users is: +as well as Plan 9, VMS, QNX, OS/2, and the Amiga. + +Although it's rumored that the (imminent) 5.004 release may build +on Windows NT, this is yet to be proven. Binary distributions +for 32-bit Microsoft systems and for Apple systems can be found +http://www.perl.com/CPAN/ports/ directory. Because these are not part of +the standard distribution, they may and in fact do differ from the base +Perl port in a variety of ways. You'll have to check their respective +release notes to see just what the differences are. These differences +can be either positive (e.g. extensions for the features of the particular +platform that are not supported in the source release of perl) or negative +(e.g. might be based upon a less current source release of perl). + +A useful FAQ for Win32 Perl users is http://www.endcontsw.com/people/evangelo/Perl_for_Win32_FAQ.html -[This FAQ is seriously outdated as of May 1998--it is only relevant to -the perl that ActiveState distributes, especially where it describes -various inadequacies and differences with the standard perl extension -build support.] =head2 How can I get a binary version of Perl? @@ -383,19 +382,6 @@ very slow to select on 18000 articles. If you have, or know where can be found, the missing sections, please let perlfaq-suggestions@perl.com know. -=head2 Perl Training - -While some large training companies offer their own courses on -Perl, you may prefer to contact individuals near and dear to -the heart of Perl development. Two well-known members of the -Perl development team head companies which offer such things -are Tom Christiansen <perl-classes@perl.com> and Randal Schwartz -<perl-training-info@stonehenge.com>, plus their respective minions, -who offer a variety of professional tutorials and seminars on Perl. -These courses include large public seminars, private corporate training, -and fly-ins to Colorado and Oregon. Contact Tom or Randal for details, -or see http://www.perl.com/perl/info/training.html on the web. - =head2 Where can I buy a commercial version of Perl? In a sense, Perl already I<is> commercial software: It has a licence diff --git a/pod/perlfaq3.pod b/pod/perlfaq3.pod index 62073e8591..11f105c48c 100644 --- a/pod/perlfaq3.pod +++ b/pod/perlfaq3.pod @@ -1,6 +1,6 @@ =head1 NAME -perlfaq3 - Programming Tools ($Revision: 1.27 $, $Date: 1998/07/05 15:07:20 $) +perlfaq3 - Programming Tools ($Revision: 1.28 $, $Date: 1998/07/16 22:08:49 $) =head1 DESCRIPTION @@ -30,14 +30,14 @@ L<perltoc> provides a crude table of contents for the perl man page set. =head2 How can I use Perl interactively? The typical approach uses the Perl debugger, described in the -perldebug(1) man page, on an "empty" program, like this: +perldebug(1) man page, on an ``empty'' program, like this: perl -de 42 Now just type in any legal Perl code, and it will be immediately evaluated. You can also examine the symbol table, get stack backtraces, check variable values, set breakpoints, and other -operations typically found in symbolic debuggers +operations typically found in symbolic debuggers. =head2 Is there a Perl shell? @@ -48,15 +48,27 @@ uninteresting, but may still be what you want. =head2 How do I debug my Perl programs? -Have you used C<-w>? +Have you used C<-w>? It enables warnings for dubious practices. -Have you tried C<use strict>? +Have you tried C<use strict>? It prevents you from using symbolic +references, makes you predeclare any subroutines that you call as bare +words, and (probably most importantly) forces you to predeclare your +variables with C<my> or C<use vars>. -Did you check the returns of each and every system call? +Did you check the returns of each and every system call? The operating +system (and thus Perl) tells you whether they worked or not, and if not +why. -Did you read L<perltrap>? + open(FH, "> /etc/cantwrite") + or die "Couldn't write to /etc/cantwrite: $!\n"; -Have you tried the Perl debugger, described in L<perldebug>? +Did you read L<perltrap>? It's full of gotchas for old and new Perl +programmers, and even has sections for those of you who are upgrading +from languages like I<awk> and I<C>. + +Have you tried the Perl debugger, described in L<perldebug>? You can +step through your program and see what it's doing and thus work out +why what it's doing isn't what it should be doing. =head2 How do I profile my Perl programs? @@ -65,6 +77,31 @@ Benchmark.pm from the standard distribution. Benchmark lets you time specific portions of your code, while Devel::DProf gives detailed breakdowns of where your code spends its time. +Here's a sample use of Benchmark: + + use Benchmark; + + @junk = `cat /etc/motd`; + $count = 10_000; + + timethese($count, { + 'map' => sub { my @a = @junk; + map { s/a/b/ } @a; + return @a + }, + 'for' => sub { my @a = @junk; + local $_; + for (@a) { s/a/b/ }; + return @a }, + }); + +This is what it prints (on one machine--your results will be dependent +on your hardware, operating system, and the load on your machine): + + Benchmark: timing 10000 iterations of for, map... + for: 4 secs ( 3.97 usr 0.01 sys = 3.98 cpu) + map: 6 secs ( 4.97 usr 0.00 sys = 4.97 cpu) + =head2 How do I cross-reference my Perl programs? The B::Xref module, shipped with the new, alpha-release Perl compiler @@ -75,21 +112,20 @@ to generate cross-reference reports for Perl programs. =head2 Is there a pretty-printer (formatter) for Perl? -There is no program that will reformat Perl as much as indent(1) will -do for C. The complex feedback between the scanner and the parser -(this feedback is what confuses the vgrind and emacs programs) makes it +There is no program that will reformat Perl as much as indent(1) does +for C. The complex feedback between the scanner and the parser (this +feedback is what confuses the vgrind and emacs programs) makes it challenging at best to write a stand-alone Perl parser. Of course, if you simply follow the guidelines in L<perlstyle>, you -shouldn't need to reformat. - -Your editor can and should help you with source formatting. The -perl-mode for emacs can provide a remarkable amount of help with most -(but not all) code, and even less programmable editors can provide -significant assistance. - -If you are used to using vgrind program for printing out nice code to -a laser printer, you can take a stab at this using +shouldn't need to reformat. The habit of formatting your code as you +write it will help prevent bugs. Your editor can and should help you +with this. The perl-mode for emacs can provide a remarkable amount of +help with most (but not all) code, and even less programmable editors +can provide significant assistance. + +If you are used to using I<vgrind> program for printing out nice code +to a laser printer, you can take a stab at this using http://www.perl.com/CPAN/doc/misc/tips/working.vgrind.entry, but the results are not particularly satisfying for sophisticated code. @@ -117,9 +153,10 @@ In the perl source directory, you'll find a directory called "emacs", which contains a cperl-mode that color-codes keywords, provides context-sensitive help, and other nifty things. -Note that the perl-mode of emacs will have fits with "main'foo" +Note that the perl-mode of emacs will have fits with C<"main'foo"> (single quote), and mess up the indentation and hilighting. You -should be using "main::foo", anyway. +should be using C<"main::foo"> in new Perl code anyway, so this +shouldn't be an issue. =head2 How can I use curses with Perl? @@ -136,6 +173,13 @@ that doesn't force you to use Tcl just to get at Tk. Sx is an interface to the Athena Widget set. Both are available from CPAN. See the directory http://www.perl.com/CPAN/modules/by-category/08_User_Interfaces/ +Invaluable for Perl/Tk programming are: the Perl/Tk FAQ at +http://w4.lns.cornell.edu/~pvhp/ptk/ptkTOC.html , the Perl/Tk Reference +Guide available at +http://www.perl.com/CPAN-local/authors/Stephen_O_Lidie/ , and the +online manpages at +http://www-users.cs.umn.edu/~amundson/perl/perltk/toc.html . + =head2 How can I generate simple menus without using CGI or Tk? The http://www.perl.com/CPAN/authors/id/SKUNZ/perlmenu.v4.0.tar.gz @@ -147,11 +191,16 @@ See the next questions. =head2 How can I make my Perl program run faster? -The best way to do this is to come up with a better algorithm. -This can often make a dramatic difference. Chapter 8 in the Camel -has some efficiency tips in it you might want to look at. +The best way to do this is to come up with a better algorithm. This +can often make a dramatic difference. Chapter 8 in the Camel has some +efficiency tips in it you might want to look at. Jon Bentley's book +``Programming Pearls'' (that's not a misspelling!) has some good tips +on optimization, too. Advice on benchmarking boils down to: benchmark +and profile to make sure you're optimizing the right part, look for +better algorithms instead of microtuning your code, and when all else +fails consider just buying faster hardware. -Other approaches include autoloading seldom-used Perl code. See the +A different approach is to autoload seldom-used Perl code. See the AutoSplit and AutoLoader modules in the standard distribution for that. Or you could locate the bottleneck and think about writing just that part in C, the way we used to take bottlenecks in C code and @@ -163,9 +212,10 @@ In some cases, it may be worth it to use the backend compiler to produce byte code (saving compilation time) or compile into C, which will certainly save compilation time and sometimes a small amount (but not much) execution time. See the question about compiling your Perl -programs. +programs for more on the compiler--the wins aren't as obvious as you'd +hope. -If you're currently linking your perl executable to a shared libc.so, +If you're currently linking your perl executable to a shared I<libc.so>, you can often gain a 10-25% performance benefit by rebuilding it to link with a static libc.a instead. This will make a bigger perl executable, but your Perl programs (and programmers) may thank you for @@ -175,7 +225,7 @@ information. Unsubstantiated reports allege that Perl interpreters that use sfio outperform those that don't (for IO intensive applications). To try this, see the F<INSTALL> file in the source distribution, especially -the "Selecting File IO mechanisms" section. +the ``Selecting File IO mechanisms'' section. The undump program was an old attempt to speed up your Perl program by storing the already-compiled form to disk. This is no longer @@ -235,8 +285,7 @@ only platform that will reliably (albeit, slowly) return memory to the OS. However, judicious use of my() on your variables will help make sure that they go out of scope so that Perl can free up their storage for -use in other parts of your program. (NB: my() variables also execute -about 10% faster than globals.) A global variable, of course, never +use in other parts of your program. A global variable, of course, never goes out of scope, so you can't get its space automatically reclaimed, although undef()ing and/or delete()ing it will achieve the same effect. In general, memory allocation and de-allocation isn't something you can @@ -252,44 +301,49 @@ to be re-compiled and will often allocate a megabyte or more of system memory, this can be a killer. Compiling into C B<isn't going to help you> because the process start-up overhead is where the bottleneck is. -There are at least two popular ways to avoid this overhead. One -solution involves running the Apache HTTP server (available from +There are two popular ways to avoid this overhead. One solution +involves running the Apache HTTP server (available from http://www.apache.org/) with either of the mod_perl or mod_fastcgi -plugin modules. With mod_perl and the Apache::* modules (from CPAN), -httpd will run with an embedded Perl interpreter which pre-compiles -your script and then executes it within the same address space without -forking. The Apache extension also gives Perl access to the internal -server API, so modules written in Perl can do just about anything a -module written in C can. With the FCGI module (from CPAN), a Perl -executable compiled with sfio (see the F<INSTALL> file in the -distribution) and the mod_fastcgi module (available from -http://www.fastcgi.com/) each of your perl scripts becomes a permanent -CGI daemon process. +plugin modules. + +With mod_perl and the Apache::Registry module (distributed with +mod_perl), httpd will run with an embedded Perl interpreter which +pre-compiles your script and then executes it within the same address +space without forking. The Apache extension also gives Perl access to +the internal server API, so modules written in Perl can do just about +anything a module written in C can. For more on mod_perl, see +http://perl.apache.org/ + +With the FCGI module (from CPAN), a Perl executable compiled with sfio +(see the F<INSTALL> file in the distribution) and the mod_fastcgi +module (available from http://www.fastcgi.com/) each of your perl +scripts becomes a permanent CGI daemon process. Both of these solutions can have far-reaching effects on your system and on the way you write your CGI scripts, so investigate them with care. -See http://www.perl.com/CPAN/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/. +See http://www.perl.com/CPAN/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/ . -A non-free, commerical product, 'The Velocity Engine for Perl', +A non-free, commerical product, ``The Velocity Engine for Perl'', (http://www.binevolve.com/ or http://www.binevolve.com/bine/vep) might also be worth looking at. It will allow you to increase the performance -of your perl scripts, upto 25 times faster than normal cgi perl by +of your perl scripts, upto 25 times faster than normal CGI perl by running in persistent perl mode, or 4 to 5 times faster without any -modification to your existing cgi scripts. Fully functional evaluation +modification to your existing CGI scripts. Fully functional evaluation copies are available from the web site. =head2 How can I hide the source for my Perl program? Delete it. :-) Seriously, there are a number of (mostly -unsatisfactory) solutions with varying levels of "security". +unsatisfactory) solutions with varying levels of ``security''. First of all, however, you I<can't> take away read permission, because the source code has to be readable in order to be compiled and interpreted. (That doesn't mean that a CGI script's source is -readable by people on the web, though.) So you have to leave the -permissions at the socially friendly 0755 level. +readable by people on the web, though, only by people with access to +the filesystem) So you have to leave the permissions at the socially +friendly 0755 level. Some people regard this as a security problem. If your program does insecure things, and relies on people not knowing how to exploit those @@ -298,8 +352,8 @@ determine the insecure things and exploit them without viewing the source. Security through obscurity, the name for hiding your bugs instead of fixing them, is little security indeed. -You can try using encryption via source filters (Filter::* from CPAN). -But crackers might be able to decrypt it. You can try using the byte +You can try using encryption via source filters (Filter::* from CPAN), +but crackers might be able to decrypt it. You can try using the byte code compiler and interpreter described below, but crackers might be able to de-compile it. You can try using the native-code compiler described below, but crackers might be able to disassemble it. These @@ -310,43 +364,42 @@ language, not just Perl). If you're concerned about people profiting from your code, then the bottom line is that nothing but a restrictive licence will give you legal security. License your software and pepper it with threatening -statements like "This is unpublished proprietary software of XYZ Corp. +statements like ``This is unpublished proprietary software of XYZ Corp. Your access to it does not give you permission to use it blah blah -blah." We are not lawyers, of course, so you should see a lawyer if +blah.'' We are not lawyers, of course, so you should see a lawyer if you want to be sure your licence's wording will stand up in court. =head2 How can I compile my Perl program into byte code or C? Malcolm Beattie has written a multifunction backend compiler, available from CPAN, that can do both these things. It is as of -Feb-1997 in late alpha release, which means it's fun to play with if +Jul-1998 in late alpha release, which means it's fun to play with if you're a programmer but not really for people looking for turn-key solutions. -I<Please> understand that merely compiling into C does not in and of -itself guarantee that your code will run very much faster. That's -because except for lucky cases where a lot of native type inferencing -is possible, the normal Perl run time system is still present and thus -will still take just as long to run and be just as big. Most programs -save little more than compilation time, leaving execution no more than -10-30% faster. A few rare programs actually benefit significantly -(like several times faster), but this takes some tweaking of your -code. +Merely compiling into C does not in and of itself guarantee that your +code will run very much faster. That's because except for lucky cases +where a lot of native type inferencing is possible, the normal Perl +run time system is still present and so your program will take just as +long to run and be just as big. Most programs save little more than +compilation time, leaving execution no more than 10-30% faster. A few +rare programs actually benefit significantly (like several times +faster), but this takes some tweaking of your code. The 5.005 release of Perl itself, whose main goal is merging the various non-Unix ports back into the one Perl source, will also have preliminary (strictly beta) support for Malcolm's compiler and his light-weight -processes (sometimes called "threads"). +processes (sometimes called ``threads''). You'll probably be astonished to learn that the current version of the compiler generates a compiled form of your script whose executable is just as big as the original perl executable, and then some. That's because as currently written, all programs are prepared for a full eval() statement. You can tremendously reduce this cost by building a -shared libperl.so library and linking against that. See the +shared I<libperl.so> library and linking against that. See the F<INSTALL> podfile in the perl source distribution for details. If you link your main perl binary with this, it will make it miniscule. -For example, on one author's system, /usr/bin/perl is only 11k in +For example, on one author's system, F</usr/bin/perl> is only 11k in size! In general, the compiler will do nothing to make a Perl program smaller, @@ -359,7 +412,7 @@ packaging, and once you see the size of what it makes (well, unless you use a shared I<libperl.so>), you'll probably want a complete Perl install anywayt. -=head2 How can I get '#!perl' to work on [MS-DOS,NT,...]? +=head2 How can I get C<#!perl> to work on [MS-DOS,NT,...]? For OS/2 just use @@ -370,11 +423,12 @@ as the first line in C<*.cmd> file (C<-S> due to a bug in cmd.exe's batch file, and codify it in C<ALTERNATIVE_SHEBANG> (see the F<INSTALL> file in the source distribution for more information). -The Win95/NT installation, when using the Activeware port of Perl, -will modify the Registry to associate the .pl extension with the perl -interpreter. If you install another port, or (eventually) build your -own Win95/NT Perl using WinGCC, then you'll have to modify the -Registry yourself. +The Win95/NT installation, when using the ActiveState port of Perl, +will modify the Registry to associate the C<.pl> extension with the +perl interpreter. If you install another port (Gurusaramy Sarathy's +is the recommended Win95/NT port), or (eventually) build your own +Win95/NT Perl using WinGCC, then you'll have to modify the Registry +yourself. Macintosh perl scripts will have the the appropriate Creator and Type, so that double-clicking them will invoke the perl application. @@ -433,10 +487,10 @@ For example: # VMS perl -e "print ""Hello world\n""" -The problem is that none of this is reliable: it depends on the command -interpreter. Under Unix, the first two often work. Under DOS, it's -entirely possible neither works. If 4DOS was the command shell, I'd -probably have better luck like this: +The problem is that none of this is reliable: it depends on the +command interpreter. Under Unix, the first two often work. Under DOS, +it's entirely possible neither works. If 4DOS was the command shell, +you'd probably have better luck like this: perl -e "print <Ctrl-x>"Hello world\n<Ctrl-x>"" @@ -445,8 +499,8 @@ shell, or MPW, is much like Unix shells in its support for several quoting variants, except that it makes free use of the Mac's non-ASCII characters as control characters. -I'm afraid that there is no general solution to all of this. It is a -mess, pure and simple. +There is no general solution to all of this. It is a mess, pure and +simple. Sucks to be away from Unix, huh? :-) [Some of this answer was contributed by Kenneth Albanowski.] @@ -454,9 +508,9 @@ mess, pure and simple. For modules, get the CGI or LWP modules from CPAN. For textbooks, see the two especially dedicated to web stuff in the question on -books. For problems and questions related to the web, like "Why -do I get 500 Errors" or "Why doesn't it run from the browser right -when it runs fine on the command line", see these sources: +books. For problems and questions related to the web, like ``Why +do I get 500 Errors'' or ``Why doesn't it run from the browser right +when it runs fine on the command line'', see these sources: WWW Security FAQ http://www.w3.org/Security/Faq/ diff --git a/pod/perlfaq4.pod b/pod/perlfaq4.pod index 21daac6fc1..0a47145a28 100644 --- a/pod/perlfaq4.pod +++ b/pod/perlfaq4.pod @@ -1,6 +1,6 @@ =head1 NAME -perlfaq4 - Data Manipulation ($Revision: 1.24 $, $Date: 1998/07/05 15:07:20 $) +perlfaq4 - Data Manipulation ($Revision: 1.25 $, $Date: 1998/07/16 22:49:55 $) =head1 DESCRIPTION @@ -17,8 +17,8 @@ only be approximate on a computer, since the computer only has a finite number of bits to store an infinite number of, um, numbers. Internally, your computer represents floating-point numbers in binary. -Floating-point numbers read in from a file, or appearing as literals -in your program, are converted from their decimal floating-point +Floating-point numbers read in from a file or appearing as literals +in your program are converted from their decimal floating-point representation (eg, 19.95) to the internal binary representation. However, 19.95 can't be precisely represented as a binary @@ -61,13 +61,20 @@ umask(), or sysopen(), which all want permissions in octal. =head2 Does perl have a round function? What about ceil() and floor()? Trig functions? -Remember that int() merely truncates toward 0. For rounding to a certain -number of digits, sprintf() or printf() is usually the easiest route. +Remember that int() merely truncates toward 0. For rounding to a +certain number of digits, sprintf() or printf() is usually the easiest +route. + + printf("%.3f", 3.1415926535); # prints 3.142 The POSIX module (part of the standard perl distribution) implements ceil(), floor(), and a number of other mathematical and trigonometric functions. + use POSIX; + $ceil = ceil(3.5); # 4 + $floor = floor(3.5); # 3 + In 5.000 to 5.003 Perls, trigonometry was done in the Math::Complex module. With 5.004, the Math::Trig module (part of the standard perl distribution) implements the trigonometric functions. Internally it @@ -83,7 +90,7 @@ need yourself. =head2 How do I convert bits into ints? -To turn a string of 1s and 0s like '10110110' into a scalar containing +To turn a string of 1s and 0s like C<10110110> into a scalar containing its binary value, use the pack() function (documented in L<perlfunc/"pack">): @@ -135,15 +142,20 @@ Get the http://www.perl.com/CPAN/modules/by-module/Roman module. =head2 Why aren't my random numbers random? -John von Neumann said, ``Anyone who attempts to generate random numbers by -deterministic means is, of course, living in a state of sin.'' - The short explanation is that you're getting pseudorandom numbers, not -random ones, because that's how these things work. A longer explanation -is available on http://www.perl.com/CPAN/doc/FMTEYEWTK/random, courtesy -of Tom Phoenix. - -You should also check out the Math::TrulyRandom module from CPAN. +random ones, because computers are good at being predictable and bad +at being random (despite appearances caused by bugs in your programs +:-). A longer explanation is available on +http://www.perl.com/CPAN/doc/FMTEYEWTK/random, courtesy of Tom +Phoenix. John von Neumann said, ``Anyone who attempts to generate +random numbers by deterministic means is, of course, living in a state +of sin.'' + +You should also check out the Math::TrulyRandom module from CPAN. It +uses the imperfections in your system's timer to generate random +numbers, but this takes quite a while. If you want a better +pseudorandom generator than comes with your operating system, look at +``Numerical Recipes in C'' at http://nr.harvard.edu/nr/bookc.html . =head1 Data: Dates @@ -163,36 +175,44 @@ You can find the week of the year by dividing this by 7: $week_of_year = int($day_of_year / 7); -Of course, this believes that weeks start at zero. +Of course, this believes that weeks start at zero. The Date::Calc +module from CPAN has a lot of date calculation functions, including +day of the year, week of the year, and so on. -=head2 How can I compare two date strings? +=head2 How can I compare two dates and find the difference? -Use the Date::Manip or Date::DateCalc modules from CPAN. +If you're storing your dates as epoch seconds then simply subtract one +from the other. If you've got a structured date (distinct year, day, +month, hour, minute, seconds values) then use one of the Date::Manip +and Date::Calc modules from CPAN. =head2 How can I take a string and turn it into epoch seconds? If it's a regular enough string that it always has the same format, -you can split it up and pass the parts to timelocal in the standard -Time::Local module. Otherwise, you should look into one of the -Date modules from CPAN. +you can split it up and pass the parts to C<timelocal> in the standard +Time::Local module. Otherwise, you should look into the Date::Calc +and Date::Manip modules from CPAN. =head2 How can I find the Julian Day? -Neither Date::Manip nor Date::DateCalc deal with Julian days. -Instead, there is an example of Julian date calculation in -http://www.perl.com/CPAN/authors/David_Muir_Sharnoff/modules/Time/JulianDay.pm.gz, -which should help. +Neither Date::Manip nor Date::Calc deal with Julian days. Instead, +there is an example of Julian date calculation that should help you in +http://www.perl.com/CPAN/authors/David_Muir_Sharnoff/modules/Time/JulianDay.pm.gz +. =head2 Does Perl have a year 2000 problem? Is Perl Y2K compliant? -Perl is just as Y2K compliant as your pencil--no more, and no less. -The date and time functions supplied with perl (gmtime and localtime) -supply adequate information to determine the year well beyond 2000 -(2038 is when trouble strikes for 32-bit machines). The year returned -by these functions when used in an array context is the year minus 1900. -For years between 1910 and 1999 this I<happens> to be a 2-digit decimal -number. To avoid the year 2000 problem simply do not treat the year as -a 2-digit number. It isn't. +Short answer: No, Perl does not have a Year 2000 problem. Yes, Perl +is Y2K compliant. + +Long answer: Perl is just as Y2K compliant as your pencil--no more, +and no less. The date and time functions supplied with perl (gmtime +and localtime) supply adequate information to determine the year well +beyond 2000 (2038 is when trouble strikes for 32-bit machines). The +year returned by these functions when used in an array context is the +year minus 1900. For years between 1910 and 1999 this I<happens> to +be a 2-digit decimal number. To avoid the year 2000 problem simply do +not treat the year as a 2-digit number. It isn't. When gmtime() and localtime() are used in scalar context they return a timestamp string that contains a fully-expanded year. For example, @@ -215,17 +235,17 @@ addresses, etc.) for details. =head2 How do I unescape a string? -It depends just what you mean by "escape". URL escapes are dealt with -in L<perlfaq9>. Shell escapes with the backslash (\) +It depends just what you mean by ``escape''. URL escapes are dealt +with in L<perlfaq9>. Shell escapes with the backslash (C<\>) character are removed with: s/\\(.)/$1/g; -Note that this won't expand \n or \t or any other special escapes. +This won't expand C<"\n"> or C<"\t"> or any other special escapes. =head2 How do I remove consecutive pairs of characters? -To turn "abbcccd" into "abccd": +To turn C<"abbcccd"> into C<"abccd">: s/(.)\1/$1/g; @@ -242,20 +262,30 @@ arbitrary expressions: print "That yields ${\($n + 5)} widgets\n"; -See also "How can I expand variables in text strings?" in this section -of the FAQ. +Version 5.004 of Perl had a bug that gave list context to the +expression in C<${...}>, but this is fixed in version 5.005. + +See also ``How can I expand variables in text strings?'' in this +section of the FAQ. =head2 How do I find matching/nesting anything? -This isn't something that can be tackled in one regular expression, no -matter how complicated. To find something between two single characters, -a pattern like C</x([^x]*)x/> will get the intervening bits in $1. For -multiple ones, then something more like C</alpha(.*?)omega/> would -be needed. But none of these deals with nested patterns, nor can they. -For that you'll have to write a parser. +This isn't something that can be done in one regular expression, no +matter how complicated. To find something between two single +characters, a pattern like C</x([^x]*)x/> will get the intervening +bits in $1. For multiple ones, then something more like +C</alpha(.*?)omega/> would be needed. But none of these deals with +nested patterns, nor can they. For that you'll have to write a +parser. + +If you are serious about writing a parser, there are a number of +modules or oddities that will make your life a lot easier. There is +the CPAN module Parse::RecDescent, the standard module Text::Balanced, +the byacc program, and Mark-Jason Dominus's excellent I<py> tool at +http://www.plover.com/~mjd/perl/py/ . -One destructive, inside-out approach that you might try is to pull -out the smallest nesting parts one at a time: +One simple destructive, inside-out approach that you might try is to +pull out the smallest nesting parts one at a time: while (s//BEGIN((?:(?!BEGIN)(?!END).)*)END/gs) { # do something with $1 @@ -287,13 +317,13 @@ Use Text::Wrap (part of the standard perl distribution): use Text::Wrap; print wrap("\t", ' ', @paragraphs); -The paragraphs you give to Text::Wrap may not contain embedded +The paragraphs you give to Text::Wrap should not contain embedded newlines. Text::Wrap doesn't justify the lines (flush-right). =head2 How can I access/change the first N letters of a string? There are many ways. If you just want to grab a copy, use -substr: +substr(): $first_byte = substr($a, 0, 1); @@ -302,15 +332,16 @@ use substr() as an lvalue: substr($a, 0, 3) = "Tom"; -Although those with a regexp kind of thought process will likely prefer +Although those with a pattern matching kind of thought process will +likely prefer: $a =~ s/^.../Tom/; =head2 How do I change the Nth occurrence of something? -You have to keep track. For example, let's say you want -to change the fifth occurrence of "whoever" or "whomever" -into "whosoever" or "whomsoever", case insensitively. +You have to keep track of N yourself. For example, let's say you want +to change the fifth occurrence of C<"whoever"> or C<"whomever"> into +C<"whosoever"> or C<"whomsoever">, case insensitively. $count = 0; s{((whom?)ever)}{ @@ -331,7 +362,7 @@ loop, keeping count of matches. } } -That prints out: "The third fish is a red one." You can also use a +That prints out: C<"The third fish is a red one."> You can also use a repetition count and repeated pattern like this: /(?:\w+\s+fish\s+){2}(\w+)\s+fish/i; @@ -364,7 +395,7 @@ To make the first letter of each word upper case: This has the strange effect of turning "C<don't do it>" into "C<Don'T Do It>". Sometimes you might want this, instead (Suggested by Brian -Foy E<lt>comdog@computerdog.comE<gt>): +Foy): $string =~ s/ ( (^\w) #at the beginning of the line @@ -384,7 +415,7 @@ To force each word to be lower case, with the first letter upper case: You can (and probably should) enable locale awareness of those characters by placing a C<use locale> pragma in your program. -See L<perllocale> for endless details. +See L<perllocale> for endless details on locales. =head2 How can I split a [character] delimited string except when inside [character]? (Comma-separated files) @@ -440,7 +471,7 @@ Or more nicely written as: s/\s+$//; } -This idiom takes advantage of the for(each) loop's aliasing +This idiom takes advantage of the C<for(each)> loop's aliasing behavior to factor out common code. You can do this on several strings at once, or arrays, or even the values of a hash if you use a slide: @@ -504,7 +535,7 @@ variables as entries in some special hash. For example: ); $text =~ s/\$(\w+)/$user_defs{$1}/g; -See also "How do I expand function calls in a string?" in this section +See also ``How do I expand function calls in a string?'' in this section of the FAQ. =head2 What's wrong with always quoting "$vars"? diff --git a/pod/perlfaq6.pod b/pod/perlfaq6.pod index 053e28496d..488a27c83a 100644 --- a/pod/perlfaq6.pod +++ b/pod/perlfaq6.pod @@ -1,6 +1,6 @@ =head1 NAME -perlfaq6 - Regexps ($Revision: 1.21 $, $Date: 1998/06/22 04:23:04 $) +perlfaq6 - Regexps ($Revision: 1.22 $, $Date: 1998/07/16 14:01:07 $) =head1 DESCRIPTION @@ -545,12 +545,10 @@ L<perlfaq2>). =head2 What's wrong with using grep or map in a void context? -Strictly speaking, nothing. Stylistically speaking, it's not a good -way to write maintainable code. That's because you're using these -constructs not for their return values but rather for their -side-effects, and side-effects can be mystifying. There's no void -grep() that's not better written as a C<for> (well, C<foreach>, -technically) loop. +Both grep and map build a return list, regardless of their context. +This means you're making Perl go to the trouble of building up a +return list that you then just ignore. That's no way to treat a +programming language, you insensitive scoundrel! =head2 How can I match strings with multibyte characters? diff --git a/pod/perlfaq7.pod b/pod/perlfaq7.pod index 2218c12685..e1bccc883f 100644 --- a/pod/perlfaq7.pod +++ b/pod/perlfaq7.pod @@ -344,7 +344,7 @@ reference to an existing or anonymous variable or function: func( \$some_scalar ); - func( \$some_array ); + func( \$some_array ); func( [ 1 .. 10 ] ); func( \%some_hash ); @@ -766,7 +766,7 @@ that includes the kind of object you were called on (which is not necessarily the same as the one in which you were compiled): sub amethod { - my $self = shift; + my $self = shift; my $class = ref($self) || $self; warn "called me from a $class object"; } diff --git a/pod/perlfaq8.pod b/pod/perlfaq8.pod index 272dd51229..e99cf426ca 100644 --- a/pod/perlfaq8.pod +++ b/pod/perlfaq8.pod @@ -848,7 +848,7 @@ different process from the shell it was started from. Changes to a process are not reflected in its parent, only in its own children created after the change. There is shell magic that may allow you to fake it by eval()ing the script's output in your shell; check out the -comp.unix.questions FAQ for details. +comp.unix.questions FAQ for details. =back diff --git a/pod/perlfaq9.pod b/pod/perlfaq9.pod index 9927152699..330158b77b 100644 --- a/pod/perlfaq9.pod +++ b/pod/perlfaq9.pod @@ -23,7 +23,7 @@ The useful FAQs and related documents are: http://www.webthing.com/page.cgi/cgifaq Web FAQ - http://www.boutell.com/faq/ + http://www.boutell.com/faq/ WWW Security FAQ http://www.w3.org/Security/Faq/ |