diff options
author | Chris 'BinGOs' Williams <chris@bingosnet.co.uk> | 2011-09-12 18:57:18 +0100 |
---|---|---|
committer | Chris 'BinGOs' Williams <chris@bingosnet.co.uk> | 2011-09-12 20:38:51 +0100 |
commit | c56bc1f68457eda03dc835055d1da96643166af7 (patch) | |
tree | b5ddf5acfe7bd1d1a07d915deb2703f4dbec6f45 /cpan/perlfaq | |
parent | 4a02128048ba336d25ccdaf0a0da3e7a7bca1173 (diff) | |
download | perl-c56bc1f68457eda03dc835055d1da96643166af7.tar.gz |
Update perlfaq to CPAN version 5.0150034
[DELTA]
5.0150034 Mon 12 Sep 2011 18:41:25 +0100
* Copy edit Perl 6 a bit more (ranguard)
* Add blog section (ranguard)
* Update much of the copy about emails in perlfaq9 (apeiron)
* Many small changes (bigpresh)
* Add descriptions to doc list (bigpresh)
* Start moving away from global file handles (shlomif)
* Typos, clarity and other cleanups (shlomif)
* Cleanup copy (ranguard)
* Start to add "my" to variables (shlomif)
* Remove verbose/history copy (ranguard)
* Switch to L<> around URLs (ranguard)
Diffstat (limited to 'cpan/perlfaq')
-rw-r--r-- | cpan/perlfaq/lib/perlfaq.pm | 2 | ||||
-rw-r--r-- | cpan/perlfaq/lib/perlfaq.pod | 92 | ||||
-rw-r--r-- | cpan/perlfaq/lib/perlfaq1.pod | 206 | ||||
-rw-r--r-- | cpan/perlfaq/lib/perlfaq2.pod | 319 | ||||
-rw-r--r-- | cpan/perlfaq/lib/perlfaq3.pod | 424 | ||||
-rw-r--r-- | cpan/perlfaq/lib/perlfaq4.pod | 422 | ||||
-rw-r--r-- | cpan/perlfaq/lib/perlfaq5.pod | 14 | ||||
-rw-r--r-- | cpan/perlfaq/lib/perlfaq6.pod | 10 | ||||
-rw-r--r-- | cpan/perlfaq/lib/perlfaq7.pod | 144 | ||||
-rw-r--r-- | cpan/perlfaq/lib/perlfaq8.pod | 208 | ||||
-rw-r--r-- | cpan/perlfaq/lib/perlfaq9.pod | 348 |
11 files changed, 1016 insertions, 1173 deletions
diff --git a/cpan/perlfaq/lib/perlfaq.pm b/cpan/perlfaq/lib/perlfaq.pm index 153db2c922..3088c57404 100644 --- a/cpan/perlfaq/lib/perlfaq.pm +++ b/cpan/perlfaq/lib/perlfaq.pm @@ -1,6 +1,6 @@ package perlfaq; { - $perlfaq::VERSION = '5.0150033'; + $perlfaq::VERSION = '5.0150034'; } 0; # not is it supposed to be loaded diff --git a/cpan/perlfaq/lib/perlfaq.pod b/cpan/perlfaq/lib/perlfaq.pod index efae64e3ee..095c436270 100644 --- a/cpan/perlfaq/lib/perlfaq.pod +++ b/cpan/perlfaq/lib/perlfaq.pod @@ -23,20 +23,20 @@ or search the perlfaq question headings: See L<perldoc> for more information. Besides your local system, you can find the perlfaq on the web, including -at http://perldoc.perl.org/ . +at L<http://perldoc.perl.org/>. The perlfaq is an evolving document and you can read the latest version -at http://faq.perl.org/ . +at L<http://faq.perl.org/>. =head2 How to contribute to the perlfaq -Please review https://github.com/perl-doc-cats/perlfaq/wiki +Please review L<https://github.com/perl-doc-cats/perlfaq/wiki>, if you do not find your suggestion please create an issue or pull request -against https://github.com/perl-doc-cats/perlfaq . +against L<https://github.com/perl-doc-cats/perlfaq>. Once approved they will then be merged into -https://github.com/tpf/perlfaq which is the latest live version that -drives http://faq.perl.org/ and will be distributed with the next +L<https://github.com/tpf/perlfaq> which is the latest live version that +drives L<http://faq.perl.org/> and will be distributed with the next release of Perl 5. =head2 What if my question isn't answered in the FAQ? @@ -48,8 +48,8 @@ it, try the resources in L<perlfaq2>. Tom Christiansen wrote the original perlfaq then expanded it with the help of Nat Torkington. brian d foy substantialy edited and expanded -the perlfaq. perlfaq-workers and others have also supplied feedback -and corrections over the years. +the perlfaq. perlfaq-workers and others have also supplied feedback, +patches and corrections over the years. =head1 AUTHOR AND COPYRIGHT @@ -91,7 +91,7 @@ them as you see fit (and at your own risk with no warranty from anyone). =head2 L<perlfaq1>: General Questions About Perl -Very general, high-level questions about Perl. +This section of the FAQ answers very general, high-level questions about Perl. =over 4 @@ -141,18 +141,10 @@ What's the difference between "perl" and "Perl"? =item * -Is it a Perl program or a Perl script? - -=item * - What is a JAPH? =item * -Where can I get a list of Larry Wall witticisms? - -=item * - How can I convince others to use Perl? =back @@ -160,13 +152,13 @@ How can I convince others to use Perl? =head2 L<perlfaq2>: Obtaining and Learning about Perl -Where to find source and documentation for Perl, support, and related matters. +This section of the FAQ answers questions about where to find source and documentation for Perl, support, and related matters. =over 4 =item * -What machines support perl? Where do I get it? +What machines support perl? Where do I get it? =item * @@ -182,15 +174,11 @@ I copied the perl binary from one machine to another, but scripts don't work. =item * -I grabbed the sources and tried to compile but gdbm/dynamic loading/malloc/linking/... failed. How do I make it work? - -=item * - -What modules and extensions are available for Perl? What is CPAN? What does CPAN/src/... mean? +I grabbed the sources and tried to compile but gdbm/dynamic loading/malloc/linking/... failed. How do I make it work? =item * -Is there an ISO or ANSI certified version of Perl? +What modules and extensions are available for Perl? What is CPAN? =item * @@ -198,11 +186,11 @@ Where can I get information on Perl? =item * -What are the Perl newsgroups on Usenet? Where do I post questions? +What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? =item * -Where should I post source code? +Where can I post questions? =item * @@ -214,30 +202,26 @@ Which magazines have Perl content? =item * -What mailing lists are there for Perl? +Which Perl blogs should I read? =item * -Where are the archives for comp.lang.perl.misc? +What mailing lists are there for Perl? =item * -Where can I buy a commercial version of perl? +Where can I buy a commercial version of Perl? =item * Where do I send bug reports? -=item * - -What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? - =back =head2 L<perlfaq3>: Programming Tools -Programmer tools and programming support. +This section of the FAQ answers questions related to programmer tools and programming support. =over 4 @@ -366,7 +350,7 @@ What's MakeMaker? =head2 L<perlfaq4>: Data Manipulation -Manipulating numbers, dates, strings, arrays, hashes, and miscellaneous data issues. +This section of the FAQ answers questions related to manipulating numbers, dates, strings, arrays, hashes, and miscellaneous data issues. =over 4 @@ -384,7 +368,7 @@ Why isn't my octal data interpreted correctly? =item * -Does Perl have a round() function? What about ceil() and floor()? Trig functions? +Does Perl have a round() function? What about ceil() and floor()? Trig functions? =item * @@ -540,7 +524,7 @@ How can I tell whether a certain element is contained in a list or array? =item * -How do I compute the difference of two arrays? How do I compute the intersection of two arrays? +How do I compute the difference of two arrays? How do I compute the intersection of two arrays? =item * @@ -687,13 +671,13 @@ How do I pack arrays of doubles or floats for XS code? =head2 L<perlfaq5>: Files and Formats -I/O and the "f" issues: filehandles, flushing, formats, and footers. +This section deals with I/O and the "f" issues: filehandles, flushing, formats, and footers. =over 4 =item * -How do I flush/unbuffer an output filehandle? Why must I do this? +How do I flush/unbuffer an output filehandle? Why must I do this? =item * @@ -725,7 +709,7 @@ How can I manipulate fixed-record-length files? =item * -How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles? +How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles? =item * @@ -765,7 +749,7 @@ Is there a leak/bug in glob()? =item * -How can I open a file with a leading ">" or trailing blanks? +How can I open a file with a leading "E<gt>" or trailing blanks? =item * @@ -813,7 +797,7 @@ How can I read in a file by paragraphs? =item * -How can I read a single character from a file? From the keyboard? +How can I read a single character from a file? From the keyboard? =item * @@ -833,7 +817,7 @@ How do I close a file descriptor by number? =item * -Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work? +Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work? =item * @@ -841,7 +825,7 @@ Why doesn't glob("*.*") get all the files? =item * -Why does Perl let me delete read-only files? Why does C<-i> clobber protected files? Isn't this a bug in Perl? +Why does Perl let me delete read-only files? Why does C<-i> clobber protected files? Isn't this a bug in Perl? =item * @@ -868,7 +852,7 @@ How do I copy an entire directory? =head2 L<perlfaq6>: Regular Expressions -This section is surprisingly small because the rest of the FAQ is littered with answers involving regular expressions. For example, decoding a URL and checking whether something is a number are handled with regular expressions, but those answers are found elsewhere in this document (in L<perlfaq9>: "How do I decode or create those %-encodings on the web" and L<perlfaq4>: "How do I determine whether a scalar is a number/whole/integer/float", to be precise). +This section is surprisingly small because the rest of the FAQ is littered with answers involving regular expressions. For example, decoding a URL and checking whether something is a number can be handled with regular expressions, but those answers are found elsewhere in this document (in perlfaq9 : "How do I decode or create those %-encodings on the web" and perlfaq4 : "How do I determine whether a scalar is a number/whole/integer/float", to be precise). =over 4 @@ -902,7 +886,7 @@ How can I make C<\w> match national character sets? =item * -How can I match a locale-smart version of C</[a-zA-Z]/>? +How can I match a locale-smart version of C</[a-zA-Z]/> ? =item * @@ -973,7 +957,7 @@ How do I match a regular expression that's in a variable? =head2 L<perlfaq7>: General Perl Language Issues -General Perl language issues that don't clearly fit into any of the other sections. +This section deals with general Perl language issues that don't clearly fit into any of the other sections. =over 4 @@ -1043,7 +1027,7 @@ How do I create a static variable? =item * -What's the difference between dynamic and lexical (static) scoping? Between local() and my()? +What's the difference between dynamic and lexical (static) scoping? Between local() and my()? =item * @@ -1102,7 +1086,7 @@ What does "bad interpreter" mean? =head2 L<perlfaq8>: System Interaction -This section of the Perl FAQ covers questions involving operating system interaction. Topics include interprocess communication (IPC), control over the user-interface (keyboard, screen and pointing devices), and most anything else not related to data manipulation. Read the FAQs and documentation specific to the port of perl to your operating system (eg, L<perlvms>, L<perlplan9>, ...). These should contain more detailed information on the vagaries of your perl. +This section of the Perl FAQ covers questions involving operating system interaction. Topics include interprocess communication (IPC), control over the user-interface (keyboard, screen and pointing devices), and most anything else not related to data manipulation. =over 4 @@ -1180,7 +1164,7 @@ How can I do an atexit() or setjmp()/longjmp()? (Exception handling) =item * -Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean? +Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean? =item * @@ -1240,7 +1224,7 @@ Is there a way to hide perl's command line from programs such as "ps"? =item * -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? +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? =item * @@ -1311,7 +1295,7 @@ What is socket.ph and where do I get it? =head2 L<perlfaq9>: Networking -Networking, the internet, and a few on the web. +This section deals with questions related to networking, the internet, and a few on the web. =over 4 @@ -1337,7 +1321,7 @@ How do I extract URLs? =item * -How do I download a file from the user's machine? How do I open a file on another machine? +How do I download a file from the user's machine? How do I open a file on another machine? =item * diff --git a/cpan/perlfaq/lib/perlfaq1.pod b/cpan/perlfaq/lib/perlfaq1.pod index c351397821..412b6bed00 100644 --- a/cpan/perlfaq/lib/perlfaq1.pod +++ b/cpan/perlfaq/lib/perlfaq1.pod @@ -10,37 +10,35 @@ about Perl. =head2 What is Perl? Perl is a high-level programming language with an eclectic heritage -written by Larry Wall and a cast of thousands. It derives from the -ubiquitous C programming language and to a lesser extent from sed, -awk, the Unix shell, and at least a dozen other tools and languages. +written by Larry Wall and a cast of thousands. + Perl's process, file, and text manipulation facilities make it particularly well-suited for tasks involving quick prototyping, system utilities, software tools, system management tasks, database access, -graphical programming, networking, and world wide web programming. -These strengths make it especially popular with system administrators -and CGI script authors, but mathematicians, geneticists, journalists, -and even managers also use Perl. Maybe you should, too. +graphical programming, networking, and web programming. + +Perl derives from the ubiquitous C programming language and to a +lesser extent from sed, awk, the Unix shell, and many other tools +and languages. + +These strengths make it especially popular with web developers +and system administrators, but mathematicians, geneticists, journalists, +and managers also use Perl. Maybe you should, too. =head2 Who supports Perl? Who develops it? Why is it free? The original culture of the pre-populist Internet and the deeply-held beliefs of Perl's author, Larry Wall, gave rise to the free and open -distribution policy of perl. Perl is supported by its users. The +distribution policy of Perl. Perl is supported by its users. The core, the standard Perl library, the optional modules, and the -documentation you're reading now were all written by volunteers. See -the personal note at the end of the README file in the perl source -distribution for more details. See L<perlhist> (new as of 5.005) -for Perl's milestone releases. +documentation you're reading now were all written by volunteers. -In particular, the core development team (known as the Perl Porters) -are a rag-tag band of highly altruistic individuals committed to +The core development team (known as the Perl Porters) +are a group of highly altruistic individuals committed to producing better software for free than you could hope to purchase for -money. You may snoop on pending developments via the archives at -http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/ -and http://archive.develooper.com/perl5-porters@perl.org/ -or the news gateway nntp://nntp.perl.org/perl.perl5.porters or -its web interface at http://nntp.perl.org/group/perl.perl5.porters , -or read the faq at http://dev.perl.org/perl5/docs/p5p-faq.html , +money. You may snoop on pending developments via the +L<archives|http://www.nntp.perl.org/group/perl.perl5.porters/> +or read the L<faq|http://dev.perl.org/perl5/docs/p5p-faq.html>, or you can subscribe to the mailing list by sending perl5-porters-subscribe@perl.org a subscription request (an empty message with no subject is fine). @@ -52,7 +50,7 @@ than GNU software's tend to be. You can get commercial support of Perl if you wish, although for most users the informal support will more than suffice. See the answer to -"Where can I buy a commercial version of perl?" for more information. +"Where can I buy a commercial version of Perl?" for more information. =head2 Which version of Perl should I use? @@ -86,7 +84,7 @@ so you'll have an easier time finding help for those. Versions prior to perl5.004 had serious security problems with buffer overflows, and in some cases have CERT advisories (for instance, -http://www.cert.org/advisories/CA-1997-17.html ). +L<http://www.cert.org/advisories/CA-1997-17.html> ). =item * @@ -109,7 +107,7 @@ as its whitewashed bones have fractured or eroded. The current leading implementation of Perl 6, Rakudo, released a "useful, usable, 'early adopter'" distribution of Perl 6 (called Rakudo Star) in July of -2010. Please see http://rakudo.org/ for more information. +2010. Please see L<http://rakudo.org/> for more information. =item * @@ -122,11 +120,8 @@ minor release (i.e. perl5.9.x, where 9 is the minor release). =back - =head2 What are Perl 4, Perl 5, or Perl 6? -(contributed by brian d foy) - In short, Perl 4 is the parent to both Perl 5 and Perl 6. Perl 5 is the older sibling, and though they are different languages, someone who knows one will spot many similarities in the other. @@ -136,56 +131,48 @@ of the perl interpreter as well as the version of the language. Each major version has significant differences that earlier versions cannot support. -The current major release of Perl is Perl 5, and was first released in +The current major release of Perl is Perl 5, first released in 1994. It can run scripts from the previous major release, Perl 4 -(March 1991), but has significant differences. It introduced the -concept of references, complex data structures, and modules. The Perl -5 interpreter was a complete re-write of the previous perl sources. - -Perl 6 was originally described as the community's rewrite of Perl 5. -Development started in 2002; syntax and design work continue to this day. As the -language has evolved, it has become clear that it is a separate language, -incompatible with Perl 5 but in the same language family. Contrary to popular -belief, Perl 6 and Perl 5 peacefully coexist with one another. That said, Perl 6 -has proven to be a fascinating source of ideas for those using Perl 5 (the Moose -object system is a well-known example). There is overlap in the communities, and -this overlap fosters the tradition of sharing and borrowing that have been -instrumental to Perl's success. The current leading implementation of Perl 6 is -Rakudo, and you can learn more about it at http://rakudo.org. +(March 1991), but has significant differences. + +Perl 6 is a reinvention of Perl, it is a language in the same lineage but +not compatible. The two are complementary, not mutually exclusive. Perl 6 is +not meant to replace Perl 5, and vice versa. See L</"What is Perl 6?"> below +to find out more. See L<perlhist> for a history of Perl revisions. =head2 What is Perl 6? -At The Second O'Reilly Open Source Software Convention, Larry Wall -announced Perl 6 development would begin in earnest. Perl 6 was an oft -used term for Chip Salzenberg's project to rewrite Perl in C++ named -Topaz. However, Topaz provided valuable insights to the next version -of Perl and its implementation, but was ultimately abandoned. +Perl 6 was I<originally> described as the community's rewrite of Perl 5. +Development started in 2002; syntax and design work continue to this day. +As the language has evolved, it has become clear that it is a separate +language, incompatible with Perl 5 but in the same language family. + +Contrary to popular belief, Perl 6 and Perl 5 peacefully coexist with one +another. Perl 6 has proven to be a fascinating source of ideas for those +using Perl 5 (the L<Moose> object system is a well-known example). There is +overlap in the communities, and this overlap fosters the tradition of sharing +and borrowing that have been instrumental to Perl's success. The current +leading implementation of Perl 6 is Rakudo, and you can learn more about +it at L<http://rakudo.org>. If you want to learn more about Perl 6, or have a desire to help in the crusade to make Perl a better place then read the Perl 6 developers -page at http://dev.perl.org/perl6/ and get involved. +page at L<http://www.perl6.org/> and get involved. "We're really serious about reinventing everything that needs reinventing." --Larry Wall -As Perl 6 is a reinvention of Perl, it is a language in the same lineage but -not compatible. The two are complementary, not mutually exclusive. Perl 6 is not -meant to replace Perl 5, and vice versa. - =head2 How stable is Perl? Production releases, which incorporate bug fixes and new functionality, are widely tested before release. Since the 5.000 release, we have -averaged only about one production release per year. +averaged about one production release per year. -Larry and the Perl development team occasionally make changes to the +The Perl development team occasionally make changes to the internal core of the language, but all possible efforts are made toward -backward compatibility. While not quite all Perl 4 scripts run flawlessly -under Perl 5, an update to perl should nearly never invalidate a program -written for an earlier version of perl (barring accidental bug fixes -and the rare new keyword). +backward compatibility. =head2 Is Perl difficult to learn? @@ -216,21 +203,25 @@ discussed in Part 2. =head2 How does Perl compare with other languages like Java, Python, REXX, Scheme, or Tcl? -Favorably in some areas, unfavorably in others. Precisely which areas -are good and bad is often a personal choice, so asking this question -on Usenet runs a strong risk of starting an unproductive Holy War. +Perl can be used for almost any coding problem, even ones which require +intergrating specialist C code for extra speed. As with any tool it can +be used well or badly. Perl has many strengths, and a few weaknesses, +precisely which areas are good and bad is often a personal choice. -Probably the best thing to do is try to write equivalent code to do a -set of tasks. These languages have their own newsgroups in which you -can learn about (but hopefully not argue about) them. +When choosing a language you should also be influenced buy the +L<resources|http://www.cpan.org/>, L<testing culture|http://www.cpantesters.org/> +and L<community|http://www.perl.org/community.html> which surrounds it. -Some comparison documents can be found at http://www.perl.com/doc/FMTEYEWTK/versus/ -if you really can't stop yourself. +For comparisons to a specific language it is often best to create +a small project in both languages and compare the results, make sure +to use all the L<resources|http://www.cpan.org/> of each language, +as a language is far more than just it's syntax. =head2 Can I do [task] in Perl? Perl is flexible and extensible enough for you to use on virtually any task, from one-line file-processing tasks to large, elaborate systems. + For many people, Perl serves as a great replacement for shell scripting. For others, it serves as a convenient, high-level replacement for most of what they'd program in low-level languages like C or C++. It's ultimately @@ -259,62 +250,18 @@ application written in another language that's all done (and done well), or you have an application language specifically designed for a certain task (e.g. prolog, make). -For various reasons, Perl is probably not well-suited for real-time -embedded systems, low-level operating systems development work like -device drivers or context-switching code, complex multi-threaded -shared-memory applications, or extremely large applications. You'll -notice that perl is not itself written in Perl. - -Perl remains fundamentally a dynamically typed language, not -a statically typed one. You certainly won't be chastised if you don't -trust nuclear-plant or brain-surgery monitoring code to it. And Larry -will sleep easier, too--Wall Street programs not withstanding. :-) +If you find that you need to speed up a specific part of a Perl +application (not something you often need) you may want to use C, +but you can access this from your Perl code with L<perlxs>. =head2 What's the difference between "perl" and "Perl"? -One bit. Oh, you weren't talking ASCII? :-) Larry now uses "Perl" to -signify the language proper and "perl" the implementation of it, i.e. -the current interpreter. Hence Tom's quip that "Nothing but perl can -parse Perl." - -Before the first edition of I<Programming perl>, people commonly -referred to the language as "perl", and its name appeared that way in -the title because it referred to the interpreter. In the book, Randal -Schwartz capitalised the language's name to make it stand out better -when typeset. This convention was adopted by the community, and the -second edition became I<Programming Perl>, using the capitalized -version of the name to refer to the language. - -You may or may not choose to follow this usage. For example, -parallelism means "awk and perl" and "Python and Perl" look good, while -"awk and Perl" and "Python and perl" do not. But never write "PERL", -because perl is not an acronym, apocryphal folklore and post-facto -expansions notwithstanding. - -=head2 Is it a Perl program or a Perl script? - -Larry doesn't really care. He says (half in jest) that "a script is -what you give the actors. A program is what you give the audience." - -Originally, a script was a canned sequence of normally interactive -commands--that is, a chat script. Something like a UUCP or PPP chat -script or an expect script fits the bill nicely, as do configuration -scripts run by a program at its start up, such F<.cshrc> or F<.ircrc>, -for example. Chat scripts were just drivers for existing programs, -not stand-alone programs in their own right. - -A computer scientist will correctly explain that all programs are -interpreted and that the only question is at what level. But if you -ask this question of someone who isn't a computer scientist, they might -tell you that a I<program> has been compiled to physical machine code -once and can then be run multiple times, whereas a I<script> must be -translated by a program each time it's used. - -Now that "script" and "scripting" are terms that have been seized by -unscrupulous or unknowing marketeers for their own nefarious purposes, -they have begun to take on strange and often pejorative meanings, -like "non serious" or "not real programming". Consequently, some Perl -programmers prefer to avoid them altogether. +"Perl" is the name of the language. Only the "P" is capitalized. +The name of the interpreter (the program which runs the Perl script) +is "perl" with a lowercase "p". + +You may or may not choose to follow this usage. But never write "PERL", +because perl is not an acronym. =head2 What is a JAPH? @@ -332,20 +279,7 @@ programs to produce the same output, spinning things quickly out of control while still providing hours of amusement for their creators and readers. -CPAN has several JAPH programs at http://www.cpan.org/misc/japh . - -=head2 Where can I get a list of Larry Wall witticisms? - -(contributed by brian d foy) - -Google "larry wall quotes"! You might even try the "I feel lucky" button. -:) - -Wikiquote has the witticisms from Larry along with their source, -including his usenet postings and source code comments. - -If you want a plain text file, try -http://www.cpan.org/misc/lwall-quotes.txt.gz . +CPAN has several JAPH programs at L<http://www.cpan.org/misc/japh>. =head2 How can I convince others to use Perl? @@ -365,8 +299,8 @@ choice and how Perl might satisfy that requirement. You don't have to worry about finding or paying for Perl; it's freely available and several popular operating systems come with Perl. Community -support in places such as Perlmonks ( http://www.perlmonks.com ) -and the various Perl mailing lists ( http://lists.perl.org ) means that +support in places such as Perlmonks ( L<http://www.perlmonks.com> ) +and the various Perl mailing lists ( L<http://lists.perl.org> ) means that you can usually get quick answers to your problems. Finally, keep in mind that Perl might not be the right tool for every @@ -379,9 +313,9 @@ You might find these links useful: =over 4 -=item * http://perltraining.com.au/whyperl.html +=item * L<http://perltraining.com.au/whyperl.html> -=item * http://www.perl.org/advocacy/whyperl.html +=item * L<http://www.perl.org/advocacy/whyperl.html> =back diff --git a/cpan/perlfaq/lib/perlfaq2.pod b/cpan/perlfaq/lib/perlfaq2.pod index 4a6d8406d6..88fb1eacec 100644 --- a/cpan/perlfaq/lib/perlfaq2.pod +++ b/cpan/perlfaq/lib/perlfaq2.pod @@ -12,7 +12,7 @@ related matters. The standard release of perl (the one maintained by the perl development team) is distributed only in source code form. You -can find the latest releases at http://www.cpan.org/src/README.html . +can find the latest releases at L<http://www.cpan.org/src/>. Perl builds and runs on a bewildering number of platforms. Virtually all known and current Unix derivatives are supported (perl's native @@ -20,7 +20,7 @@ platform), as are other systems like VMS, DOS, OS/2, Windows, QNX, BeOS, OS X, MPE/iX and the Amiga. Binary distributions for some proprietary platforms can be found -http://www.cpan.org/ports/ directory. Because these are not part of +L<http://www.cpan.org/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 @@ -35,23 +35,14 @@ See L<CPAN Ports|http://www.cpan.org/ports/> =head2 I don't have a C compiler. How can I build my own Perl interpreter? -Since you don't have a C compiler, you're doomed and your vendor -should be sacrificed to the Sun gods. But that doesn't help you. +For Windows, use a binary version of Perl, +L<Strawberry Perl|http://strawberryperl.com/> and +L<ActivePerl|http://www.activestate.com/activeperl> come with a +bundled C compiler. -What you need to do is get a binary version of C<gcc> for your system -first. Consult the Usenet FAQs for your operating system for -information on where to get such a binary version. - -You might look around the net for a pre-built binary of Perl (or a -C compiler!) that meets your needs, though: - -For Windows, L<Vanilla Perl|http://vanillaperl.com/> and -L<Strawberry Perl|http://strawberryperl.com/> come with a -bundled C compiler. ActivePerl is a pre-compiled version of Perl -ready-to-use. - -For Sun systems, SunFreeware.com provides binaries of most popular -applications, including compilers and Perl. +Otherwise if you really do want to build Perl, you need to get a +binary version of C<gcc> for your system first. Use a search +engine to find out how to do this for your operating system. =head2 I copied the perl binary from one machine to another, but scripts don't work. @@ -82,210 +73,132 @@ It describes in detail how to cope with most idiosyncrasies that the C<Configure> script can't work around for any given system or architecture. -=head2 What modules and extensions are available for Perl? What is CPAN? What does CPAN/src/... mean? +=head2 What modules and extensions are available for Perl? What is CPAN? CPAN stands for Comprehensive Perl Archive Network, a multi-gigabyte archive replicated on hundreds of machines all over the world. CPAN -contains source code, non-native ports, documentation, scripts, and -many third-party modules and extensions, designed for everything from -commercial database interfaces to keyboard/screen control to web -walking and CGI scripts. The master web site for CPAN is -http://www.cpan.org/ and there is the CPAN Multiplexer at -http://www.cpan.org/CPAN.html which will choose a mirror near you via -DNS. See http://www.perl.com/CPAN (without a slash at the end) for -how this process works. Also, http://mirror.cpan.org/ has a nice -interface to the http://www.cpan.org/MIRRORED.BY mirror directory. - -See the CPAN FAQ at http://www.cpan.org/misc/cpan-faq.html for answers -to the most frequently asked questions about CPAN including how to -become a mirror. - -F<CPAN/path/...> is a naming convention for files available on CPAN -sites. CPAN indicates the base directory of a CPAN mirror, and the -rest of the path is the path from that directory to the file. For -instance, if you're using ftp://ftp.funet.fi/pub/languages/perl/CPAN -as your CPAN site, the file F<CPAN/misc/japh> is downloadable as -ftp://ftp.funet.fi/pub/languages/perl/CPAN/misc/japh . - -Considering that, as of 2006, there are over ten thousand existing -modules in the archive, one probably exists to do nearly anything you -can think of. Current categories under C<CPAN/modules/by-category/> -include Perl core modules; development support; operating system -interfaces; networking, devices, and interprocess communication; data -type utilities; database interfaces; user interfaces; interfaces to -other languages; filenames, file systems, and file locking; -internationalization and locale; world wide web support; server and -daemon utilities; archiving and compression; image manipulation; mail -and news; control flow utilities; filehandle and I/O; Microsoft -Windows modules; and miscellaneous modules. - -See http://www.cpan.org/modules/00modlist.long.html or -http://search.cpan.org/ for a more complete list of modules by -category. - -CPAN is a free service and is not affiliated with O'Reilly Media. - -=head2 Is there an ISO or ANSI certified version of Perl? - -Certainly not. Larry expects that he'll be certified before Perl is. +contains tens of thousands of modules and extensions, source code +and documentation, designed for I<everything> from commercial +database interfaces to keyboard/screen control and running large web sites. + +You can search CPAN on L<http://metacpan.org> or +L<http://search.cpan.org/>. + +The master web site for CPAN is L<http://www.cpan.org/>, +L<http://www.cpan.org/SITES.html> lists all mirrors. + +See the CPAN FAQ at L<http://www.cpan.org/misc/cpan-faq.html> for answers +to the most frequently asked questions about CPAN. + +The L<Task::Kensho> module has a list of recommended modules which +you should review as a good starting point. =head2 Where can I get information on Perl? +=over 4 + +=item * L<http://www.perl.org/> + +=item * L<http://perldoc.perl.org/> + +=item * L<http://learn.perl.org/> + +=item * L<http://faq.perl.org/> + +=back + The complete Perl documentation is available with the Perl distribution. If you have Perl installed locally, you probably have the documentation -installed as well: type C<man perl> if you're on a system resembling Unix. -This will lead you to other important man pages, including how to set your -C<$MANPATH>. If you're not on a Unix system, access to the documentation -will be different; for example, documentation might only be in HTML format. All -proper perl installations have fully-accessible documentation. - -You might also try C<perldoc perl> in case your system doesn't -have a proper C<man> command, or it's been misinstalled. If that doesn't -work, try looking in C</usr/local/lib/perl5/pod> for documentation. +installed as well: type C<perldoc perl> in a terminal or +L<view online|http://perldoc.perl.org/perl.html>. -If all else fails, consult http://perldoc.perl.org/ which has the -complete documentation in HTML and PDF format. +(Some operating system distributions may ship the documentation in a different +package; for instance, on Debian, you need to install the C<perl-doc> package.) Many good books have been written about Perl--see the section later in L<perlfaq2> for more details. -Tutorial documents included in current or upcoming Perl releases -include L<perlootut> for objects, L<perlopentut> for file opening semantics, -L<perlreftut> for managing references, L<perlretut> for regular -expressions, L<perlthrtut> for threads, L<perldebtut> for debugging, -and L<perlxstut> for linking C and Perl together. There may be more -by the time you read this. These URLs might also be useful: - -=over 4 - -=item * L<Perldoc|http://perldoc.perl.org/> +=head2 What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? -=item * L<Perl.org|http://www.perl.org/> +L<Perl.com|http://www.perl.com/> used to be part of the O'Reilly +Network, a subsidiary of O'Reilly Media. Although it retains most of +the original content from its O'Reilly Network, it is now hosted by +L<The Perl Foundation|http://www.perlfoundation.org/>. -=item * L<Learn.perl.org|http://learn.perl.org/> +The Perl Foundation is an advocacy organization for the Perl language +which maintains the web site L<http://www.perl.org/> as a general +advocacy site for the Perl language. It uses the domain to provide +general support services to the Perl community, including the hosting +of mailing lists, web sites, and other services. There are also many +other sub-domains for special topics like learning Perl and jobs in Perl, +such as: -=back +=over 4 -=head2 What are the Perl newsgroups on Usenet? Where do I post questions? +=item * L<http://www.perl.org/> -Several groups devoted to the Perl language are on Usenet: +=item * L<http://learn.perl.org/> - comp.lang.perl.announce Moderated announcement group - comp.lang.perl.misc High traffic general Perl discussion - comp.lang.perl.moderated Moderated discussion group - comp.lang.perl.modules Use and development of Perl modules - comp.lang.perl.tk Using Tk (and X) from Perl +=item * L<http://jobs.perl.org/> -Some years ago, comp.lang.perl was divided into those groups, and -comp.lang.perl itself officially removed. While that group may still -be found on some news servers, it is unwise to use it, because -postings there will not appear on news servers which honour the -official list of group names. Use comp.lang.perl.misc for topics -which do not have a more-appropriate specific group. +=item * L<http://lists.perl.org/> -There is also a Usenet gateway to Perl mailing lists sponsored by -perl.org at nntp://nntp.perl.org , a web interface to the same lists -at http://nntp.perl.org/group/ and these lists are also available -under the C<perl.*> hierarchy at http://groups.google.com . Other -groups are listed at http://lists.perl.org/ ( also known as -http://lists.cpan.org/ ). +=back -A nice place to ask questions is the PerlMonks site, -http://www.perlmonks.org/ , or the Perl Beginners mailing list -http://lists.perl.org/showlist.cgi?name=beginners . +L<Perl Mongers|http://www.pm.org/> uses the pm.org domain for services +related to local Perl user groups, including the hosting of mailing lists +and web sites. See the L<Perl Mongers website|http://www.pm.org/> for more +information about joining, starting, or requesting services for a +Perl user group. -Note that none of the above are supposed to write your code for you: -asking questions about particular problems or general advice is fine, -but asking someone to write your code for free is not very cool. +CPAN, or the Comprehensive Perl Archive Network L<http://www.cpan.org/>, +is a replicated, worldwide repository of Perl software. +See L<What is CPAN?|/"What modules and extensions are available for Perl? What is CPAN? What does CPANE<sol>srcE<sol>... mean?">. -=head2 Where should I post source code? +=head2 Where can I post questions? -You should post source code to whichever group is most appropriate, but -feel free to cross-post to comp.lang.perl.misc. If you want to cross-post -to alt.sources, please make sure it follows their posting standards, -including setting the Followup-To header line to NOT include alt.sources; -see their FAQ ( http://www.faqs.org/faqs/alt-sources-intro/ ) for details. +There are many Perl L<mailing lists|lists.perl.org> for various +topics, specifically the L<beginners list|http://lists.perl.org/list/beginners.html> +may be of use. -If you're just looking for software, first use Google -( http://www.google.com ), Google's Usenet search interface -( http://groups.google.com ), and CPAN Search ( http://search.cpan.org ). -This is faster and more productive than just posting a request. +Other places to ask questions are on the +L<PerlMonks site|http://www.perlmonks.org/> or +L<stackoverflow|http://stackoverflow.com/questions/tagged/perl>. =head2 Perl Books -There are many good books on Perl. See the L<perlbook> documentation or -( http://books.perl.org ). +There are many good L<books on Perl|http://www.perl.org/books/library.html>. =head2 Which magazines have Perl content? There's also I<$foo Magazin>, a German magazine dedicated to Perl, at -( http://www.foo-magazin.de ). The I<Perl-Zeitung> is another +( L<http://www.foo-magazin.de> ). The I<Perl-Zeitung> is another German-speaking magazine for Perl beginners (see -http://perl-zeitung.at.tf ). - -Magazines that frequently carry quality articles on Perl include -I<Unix Review> ( http://www.unixreview.com/ ), I<Linux Magazine> ( -http://www.linuxmagazine.com/ ), and Usenix's newsletter/magazine to -its members, I<login:> ( http://www.usenix.org/ ). - -The Perl columns of Randal L. Schwartz are available on the web at -http://www.stonehenge.com/merlyn/WebTechniques/ , -http://www.stonehenge.com/merlyn/UnixReview/ , and -http://www.stonehenge.com/merlyn/LinuxMag/ . - -The first (and for a long time, only) periodical devoted to All Things -Perl, I<The Perl Journal> contains tutorials, demonstrations, case -studies, announcements, contests, and much more. I<TPJ> has columns -on web development, databases, Win32 Perl, graphical programming, -regular expressions, and networking, and sponsors the Obfuscated Perl -Contest and the Perl Poetry Contests. Beginning in November 2002, I<TPJ> -moved to a reader-supported monthly e-zine format in which subscribers -can download issues as PDF documents. In 2006, I<TPJ> merged with Dr. -Dobbs Journal (online edition). To read old I<TPJ> articles, see -http://www.ddj.com/ or brian d foy's index of online TPJ content -( http://www.perlmonks.org/index.pl?node_id=711609 ). +L<http://perl-zeitung.at.tf> ). -=head2 What mailing lists are there for Perl? - -Most of the major modules (L<Tk>, L<CGI>, L<libwww-perl>) have their own -mailing lists. Consult the documentation that came with the module for -subscription information. - -A comprehensive list of Perl-related mailing lists can be found at -http://lists.perl.org/ +Several unix/linux releated magazines frequently includes articles on Perl. -=head2 Where are the archives for comp.lang.perl.misc? +=head2 Which Perl blogs should I read? -The Google search engine now carries archived and searchable newsgroup -content. +L<http://blogs.perl.org/> hosts many Perl blogs, there are also +several blog aggregators: L<Perlsphere|http://perlsphere.net/> and +L<IronMan|http://ironman.enlightenedperl.org/> are two of them. -http://groups.google.com/group/comp.lang.perl.misc/topics +=head2 What mailing lists are there for Perl? -If you have a question, you can be sure someone has already asked the -same question at some point on c.l.p.m. It requires some time and patience -to sift through all the content but often you will find the answer you -seek. +A comprehensive list of Perl-related mailing lists can be found at +L<http://lists.perl.org/> -=head2 Where can I buy a commercial version of perl? +=head2 Where can I buy a commercial version of Perl? -In a real sense, perl already I<is> commercial software: it has a license +Perl already I<is> commercial software: it has a license that you can grab and carefully read to your manager. It is distributed in releases and comes in well-defined packages. There is a very large -user community and an extensive literature. The comp.lang.perl.* -newsgroups and several of the mailing lists provide free answers to your -questions in near real-time. Perl has traditionally been supported by -Larry, scores of software designers and developers, and myriad -programmers, all working for free to create a useful thing to make life -better for everyone. - -However, these answers may not suffice for managers who require a -purchase order from a company whom they can sue should anything go awry. -Or maybe they need very serious hand-holding and contractual obligations. -Shrink-wrapped CDs with perl on them are available from several sources if -that will help. For example, many Perl books include a distribution of perl, -as do the O'Reilly Perl Resource Kits (in both the Unix flavor -and in the proprietary Microsoft flavor); the free Unix distributions -also all come with perl. +and supportive user community and an extensive literature. + +If you still need commercial support +L<ActiveState|http://www.activestate.com/activeperl> offers +this. =head2 Where do I send bug reports? @@ -301,13 +214,11 @@ information about your installation to include with your message, then sends the message to the right place. To determine if a module came with your version of Perl, you can -use the L<Module::CoreList> module. It has the information about -the modules (with their versions) included with each release of Perl. - -If L<Module::CoreList> is not installed on your system, check out -http://perlpunks.de/corelist . +install and use the L<Module::CoreList> module. It has the information +about the modules (with their versions) included with each release +of Perl. -Every CPAN module has a bug tracker set up in RT, http://rt.cpan.org . +Every CPAN module has a bug tracker set up in RT, L<http://rt.cpan.org>. You can submit bugs to RT either through its web interface or by email. To email a bug report, send it to bug-E<lt>distribution-nameE<gt>@rt.cpan.org . For example, if you @@ -315,45 +226,9 @@ wanted to report a bug in L<Business::ISBN>, you could send a message to bug-Business-ISBN@rt.cpan.org . Some modules might have special reporting requirements, such as a -Sourceforge or Google Code tracking system, so you should check the +Github or Google Code tracking system, so you should check the module documentation too. -=head2 What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org? - -L<Perl.com|http://www.perl.com/> used to be part of the O'Reilly -Network, a subsidiary of O'Reilly Media. Although it retains most of -the original content from its O'Reilly Network, it is now hosted by -The Perl Foundation. - -The Perl Foundation is an advocacy organization for the Perl language -which maintains the web site L<Perl.org|http://www.perl.org/> as a general -advocacy site for the Perl language. It uses the domain to provide -general support services to the Perl community, including the hosting -of mailing lists, web sites, and other services. There are also many -other sub-domains for special topics like learning Perl, Perl news, -jobs in Perl, such as: - -=over 4 - -=item * L<Perl.org|http://www.perl.org/> - -=item * L<Learn.perl.org|http://learn.perl.org/> - -=item * L<Jobs.perl.org|http://jobs.perl.org/> - -=item * L<Lists.perl.org|http://lists.perl.org/> - -=back - -Perl Mongers uses the pm.org domain for services related to Perl user -groups, including the hosting of mailing lists and web sites. See the -L<Perl Mongers website|http://www.pm.org/> for more information about -joining, starting, or requesting services for a Perl user group. - -CPAN, or the L<Comprehensive Perl Archive Network|http://www.cpan.org/>, -is a replicated, worldwide repository of Perl software. -See L<What is CPAN?|/"What modules and extensions are available for Perl? What is CPAN? What does CPANE<sol>srcE<sol>... mean?">. - =head1 AUTHOR AND COPYRIGHT Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and diff --git a/cpan/perlfaq/lib/perlfaq3.pod b/cpan/perlfaq/lib/perlfaq3.pod index 9772349b0f..5afcf7c680 100644 --- a/cpan/perlfaq/lib/perlfaq3.pod +++ b/cpan/perlfaq/lib/perlfaq3.pod @@ -9,51 +9,131 @@ and programming support. =head2 How do I do (anything)? -Have you looked at CPAN (see L<perlfaq2>)? The chances are that +Have you looked at CPAN (see L<perlfaq2>)? The chances are that someone has already written a module that can solve your problem. -Have you read the appropriate manpages? Here's a brief index: +Have you read the appropriate manpages? Here's a brief index: =over 4 =item Basics -perldata, perlvar, perlsyn, perlop, perlsub +=over 4 + +=item L<perldata> - Perl data types + +=item L<perlvar> - Perl pre-defined variables + +=item L<perlsyn> - Perl syntax + +=item L<perlop> - Perl operators and precedence + +=item L<perlsub> - Perl subroutines + +=back + =item Execution -perlrun, perldebug +=over 4 + +=item L<perlrun> - how to execute the Perl interpreter + +=item L<perldebug> - Perl debugging + +=back + =item Functions -perlfunc +=over 4 + +=item L<perlfunc> - Perl builtin functions + +=back =item Objects -perlref, perlmod, perlobj, perltie +=over 4 + +=item L<perlref> - Perl references and nested data structures + +=item L<perlmod> - Perl modules (packages and symbol tables) + +=item L<perlobj> - Perl objects + +=item L<perltie> - how to hide an object class in a simple variable + +=back + =item Data Structures -perlref, perllol, perldsc +=over 4 + +=item L<perlref> - Perl references and nested data structures + +=item L<perllol> - Manipulating arrays of arrays in Perl + +=item L<perldsc> - Perl Data Structures Cookbook + +=back =item Modules -perlmod, perlmodlib, perlsub +=over 4 + +=item L<perlmod> - Perl modules (packages and symbol tables) + +=item L<perlmodlib> - constructing new Perl modules and finding existing ones + +=back + =item Regexes -perlre, perlfunc, perlop, perllocale +=over 4 + +=item L<perlre> - Perl regular expressions + +=item L<perlfunc> - Perl builtin functions> + +=item L<perlop> - Perl operators and precedence + +=item L<perllocale> - Perl locale handling (internationalization and localization) + +=back + =item Moving to perl5 -perltrap, perl +=over 4 + +=item L<perltrap> - Perl traps for the unwary + +=item L<perl> + +=back + =item Linking with C -perlxstut, perlxs, perlcall, perlguts, perlembed +=over 4 + +=item L<perlxstut> - Tutorial for writing XSUBs + +=item L<perlxs> - XS language reference manual + +=item L<perlcall> - Perl calling conventions from C + +=item L<perlguts> - Introduction to the Perl API + +=item L<perlembed> - how to embed perl in your C program + +=back =item Various -http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz +L<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> (not a man-page but still useful, a collection of various essays on Perl techniques) @@ -69,10 +149,15 @@ L<perldebug(1)> manpage, 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 +evaluated. You can also examine the symbol table, get stack backtraces, check variable values, set breakpoints, and other operations typically found in symbolic debuggers. +You can also use L<Devel::REPL> which is an interactive shell for Perl, +commonly known as a REPL - Read, Evaluate, Print, Loop. It provides +various handy features. + + =head2 Is there a Perl shell? The L<psh> (Perl sh) is currently at version 1.8. The Perl Shell is a shell @@ -80,15 +165,15 @@ that combines the interactive nature of a Unix shell with the power of Perl. The goal is a full-featured shell that behaves as expected for normal shell activity and uses Perl syntax and functionality for control-flow statements and other things. You can get L<psh> at -https://metacpan.org/release/psh . +L<https://metacpan.org/release/psh> . L<Zoidberg> is a similar project and provides a shell written in perl, configured in perl and operated in perl. It is intended as a login shell and development environment. It can be found at -https://metacpan.org/release/Zoidberg. +L<https://metacpan.org/release/Zoidberg>. The C<Shell.pm> module (distributed with Perl) makes Perl try commands -which aren't part of the Perl language as shell commands. C<perlsh> from +which aren't part of the Perl language as shell commands. C<perlsh> from the source distribution is simplistic and uninteresting, but may still be what you want. @@ -105,7 +190,7 @@ that C<CPAN.pm> understands and can use to re-install every module: Inside a Perl program, you can use the L<ExtUtils::Installed> module to show all installed distributions, although it can take awhile to do -its magic. The standard library which comes with Perl just shows up +its magic. The standard library which comes with Perl just shows up as "Perl" (although you can get those with L<Module::CoreList>). use ExtUtils::Installed; @@ -146,7 +231,7 @@ with L<File::Find> which is part of the standard library: print join "\n", @files; If you simply need to check quickly to see if a module is -available, you can check for its documentation. If you can +available, you can check for its documentation. If you can read the documentation the module is most likely installed. If you cannot read the documentation, the module might not have any (in rare cases): @@ -158,6 +243,9 @@ perl finds it: $ perl -MModule::Name -e1 +(If you don't receive a "Can't locate ... in @INC" error message, then Perl +found the module name you asked for.) + =head2 How do I debug my Perl programs? (contributed by brian d foy) @@ -225,19 +313,19 @@ or I<Mastering Perl>, chapter 5. L<perldebguts> documents creating a custom debugger if you need to create a special sort of profiler. brian d foy describes the process in I<The Perl Journal>, "Creating a Perl Debugger", -http://www.ddj.com/184404522 , and "Profiling in Perl" -http://www.ddj.com/184404580 . +L<http://www.ddj.com/184404522> , and "Profiling in Perl" +L<http://www.ddj.com/184404580> . Perl.com has two interesting articles on profiling: "Profiling Perl", -by Simon Cozens, http://www.perl.com/lpt/a/850 and "Debugging and +by Simon Cozens, L<http://www.perl.com/lpt/a/850> and "Debugging and Profiling mod_perl Applications", by Frank Wiles, -http://www.perl.com/pub/a/2006/02/09/debug_mod_perl.html . +L<http://www.perl.com/pub/a/2006/02/09/debug_mod_perl.html> . Randal L. Schwartz writes about profiling in "Speeding up Your Perl Programs" for I<Unix Review>, -http://www.stonehenge.com/merlyn/UnixReview/col49.html , and "Profiling +L<http://www.stonehenge.com/merlyn/UnixReview/col49.html> , and "Profiling in Template Toolkit via Overriding" for I<Linux Magazine>, -http://www.stonehenge.com/merlyn/LinuxMag/col75.html . +L<http://www.stonehenge.com/merlyn/LinuxMag/col75.html> . =head2 How do I cross-reference my Perl programs? @@ -254,22 +342,22 @@ the rules of the L<perlstyle>. If you write Perl, or spend much time reading Perl, you will probably find it useful. Of course, if you simply follow the guidelines in L<perlstyle>, -you 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 or newer cperl-mode for emacs +you 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 or newer cperl-mode for emacs can provide remarkable amounts of help with most (but not all) code, and even less programmable editors can provide significant -assistance. Tom Christiansen and many other VI users swear by +assistance. Tom Christiansen and many other VI users swear by the following settings in vi and its clones: set ai sw=4 map! ^O {^M}^[O^T Put that in your F<.exrc> file (replacing the caret characters -with control characters) and away you go. In insert mode, ^T is +with control characters) and away you go. In insert mode, ^T is for indenting, ^D is for undenting, and ^O is for blockdenting--as -it were. A more complete example, with comments, can be found at -http://www.cpan.org/authors/id/TOMC/scripts/toms.exrc.gz +it were. A more complete example, with comments, can be found at +L<http://www.cpan.org/authors/id/TOMC/scripts/toms.exrc.gz> =head2 Is there a ctags for Perl? @@ -279,17 +367,17 @@ Ctags uses an index to quickly find things in source code, and many popular editors support ctags for several different languages, including Perl. -Exuberant ctags supports Perl: http://ctags.sourceforge.net/ +Exuberant ctags supports Perl: L<http://ctags.sourceforge.net/> -You might also try pltags: http://www.mscha.com/pltags.zip +You might also try pltags: L<http://www.mscha.com/pltags.zip> =head2 Is there an IDE or Windows Perl Editor? Perl programs are just plain text, so any editor will do. -If you're on Unix, you already have an IDE--Unix itself. The Unix +If you're on Unix, you already have an IDE--Unix itself. The Unix philosophy is the philosophy of several small tools that each do one -thing and do it well. It's like a carpenter's toolbox. +thing and do it well. It's like a carpenter's toolbox. If you want an IDE, check the following (in alphabetical order, not order of preference): @@ -298,14 +386,14 @@ order of preference): =item Eclipse -http://e-p-i-c.sf.net/ +L<http://e-p-i-c.sf.net/> The Eclipse Perl Integration Project integrates Perl editing/debugging with Eclipse. =item Enginsite -http://www.enginsite.com/ +L<http://www.enginsite.com/> Perl Editor by EngInSite is a complete integrated development environment (IDE) for creating, testing, and debugging Perl scripts; @@ -313,7 +401,7 @@ the tool runs on Windows 9x/NT/2000/XP or later. =item Komodo -http://www.ActiveState.com/Products/Komodo/ +L<http://www.ActiveState.com/Products/Komodo/> ActiveState's cross-platform (as of October 2004, that's Windows, Linux, and Solaris), multi-language IDE has Perl support, including a regular expression @@ -321,11 +409,11 @@ debugger and remote debugging. =item Notepad++ -http://notepad-plus.sourceforge.net/ +L<http://notepad-plus.sourceforge.net/> =item Open Perl IDE -http://open-perl-ide.sourceforge.net/ +L<http://open-perl-ide.sourceforge.net/> Open Perl IDE is an integrated development environment for writing and debugging Perl scripts with ActiveState's ActivePerl distribution @@ -333,40 +421,40 @@ under Windows 95/98/NT/2000. =item OptiPerl -http://www.optiperl.com/ +L<http://www.optiperl.com/> OptiPerl is a Windows IDE with simulated CGI environment, including debugger and syntax-highlighting editor. =item Padre -http://padre.perlide.org/ +L<http://padre.perlide.org/> Padre is cross-platform IDE for Perl written in Perl using wxWidgets to provide a native look and feel. It's open source under the Artistic License. =item PerlBuilder -http://www.solutionsoft.com/perl.htm +L<http://www.solutionsoft.com/perl.htm> PerlBuilder is an integrated development environment for Windows that supports Perl development. =item visiPerl+ -http://helpconsulting.net/visiperl/index.html +L<http://helpconsulting.net/visiperl/index.html> From Help Consulting, for Windows. =item Visual Perl -http://www.activestate.com/Products/Visual_Perl/ +L<http://www.activestate.com/Products/Visual_Perl/> Visual Perl is a Visual Studio.NET plug-in from ActiveState. =item Zeus -http://www.zeusedit.com/lookmain.html +L<http://www.zeusedit.com/lookmain.html> Zeus for Window is another Win32 multi-language editor/IDE that comes with support for Perl. @@ -384,32 +472,32 @@ Microsoft Word or WordPerfect, typically do not work since they insert all sorts of behind-the-scenes information, although some allow you to save files as "Text Only". You can also download text editors designed specifically for programming, such as Textpad ( -http://www.textpad.com/ ) and UltraEdit ( http://www.ultraedit.com/ ), +L<http://www.textpad.com/> ) and UltraEdit ( L<http://www.ultraedit.com/> ), among others. If you are using MacOS, the same concerns apply. MacPerl (for Classic environments) comes with a simple editor. Popular external editors are -BBEdit ( http://www.bbedit.com/ ) or Alpha ( -http://www.his.com/~jguyer/Alpha/Alpha8.html ). MacOS X users can use +BBEdit ( L<http://www.bbedit.com/> ) or Alpha ( +L<http://www.his.com/~jguyer/Alpha/Alpha8.html> ). MacOS X users can use Unix editors as well. =over 4 =item GNU Emacs -http://www.gnu.org/software/emacs/windows/ntemacs.html +L<http://www.gnu.org/software/emacs/windows/ntemacs.html> =item MicroEMACS -http://www.microemacs.de/ +L<http://www.microemacs.de/> =item XEmacs -http://www.xemacs.org/Download/index.html +L<http://www.xemacs.org/Download/index.html> =item Jed -http://space.mit.edu/~davis/jed/ +L<http://space.mit.edu/~davis/jed/> =back @@ -419,11 +507,11 @@ or a vi clone such as =item Vim -http://www.vim.org/ +L<http://www.vim.org/> =item Vile -http://dickey.his.com/vile/vile.html +L<http://dickey.his.com/vile/vile.html> =back @@ -433,57 +521,57 @@ The following are Win32 multilanguage editor/IDEs that support Perl: =item Codewright -http://www.borland.com/codewright/ +L<http://www.borland.com/codewright/> =item MultiEdit -http://www.MultiEdit.com/ +L<http://www.MultiEdit.com/> =item SlickEdit -http://www.slickedit.com/ +L<http://www.slickedit.com/> =item ConTEXT -http://www.contexteditor.org/ +L<http://www.contexteditor.org/> =back There is also a toyedit Text widget based editor written in Perl -that is distributed with the Tk module on CPAN. The ptkdb -( http://ptkdb.sourceforge.net/ ) is a Perl/Tk-based debugger that -acts as a development environment of sorts. Perl Composer -( http://perlcomposer.sourceforge.net/ ) is an IDE for Perl/Tk +that is distributed with the Tk module on CPAN. The ptkdb +( L<http://ptkdb.sourceforge.net/> ) is a Perl/Tk-based debugger that +acts as a development environment of sorts. Perl Composer +( L<http://perlcomposer.sourceforge.net/> ) is an IDE for Perl/Tk GUI creation. In addition to an editor/IDE you might be interested in a more -powerful shell environment for Win32. Your options include +powerful shell environment for Win32. Your options include =over 4 =item Bash -from the Cygwin package ( http://sources.redhat.com/cygwin/ ) +from the Cygwin package ( L<http://sources.redhat.com/cygwin/> ) =item Ksh -from the MKS Toolkit ( http://www.mkssoftware.com/ ), or the Bourne shell of -the U/WIN environment ( http://www.research.att.com/sw/tools/uwin/ ) +from the MKS Toolkit ( L<http://www.mkssoftware.com/> ), or the Bourne shell of +the U/WIN environment ( L<http://www.research.att.com/sw/tools/uwin/> ) =item Tcsh -ftp://ftp.astron.com/pub/tcsh/ , see also -http://www.primate.wisc.edu/software/csh-tcsh-book/ +L<ftp://ftp.astron.com/pub/tcsh/> , see also +L<http://www.primate.wisc.edu/software/csh-tcsh-book/> =item Zsh -http://www.zsh.org/ +L<http://www.zsh.org/> =back MKS and U/WIN are commercial (U/WIN is free for educational and research purposes), Cygwin is covered by the GNU General Public -License (but that shouldn't matter for Perl use). The Cygwin, MKS, +License (but that shouldn't matter for Perl use). The Cygwin, MKS, and U/WIN all contain (in addition to the shells) a comprehensive set of standard Unix toolkit utilities. @@ -492,7 +580,7 @@ be sure to transfer them in ASCII mode so the ends of lines are appropriately converted. On Mac OS the MacPerl Application comes with a simple 32k text editor -that behaves like a rudimentary IDE. In contrast to the MacPerl Application +that behaves like a rudimentary IDE. In contrast to the MacPerl Application the MPW Perl tool can make use of the MPW Shell itself as an editor (with no 32k limit). @@ -501,48 +589,48 @@ no 32k limit). =item Affrus is a full Perl development environment with full debugger support -( http://www.latenightsw.com ). +( L<http://www.latenightsw.com> ). =item Alpha is an editor, written and extensible in Tcl, that nonetheless has built-in support for several popular markup and programming languages, -including Perl and HTML ( http://www.his.com/~jguyer/Alpha/Alpha8.html ). +including Perl and HTML ( L<http://www.his.com/~jguyer/Alpha/Alpha8.html> ). =item BBEdit and BBEdit Lite are text editors for Mac OS that have a Perl sensitivity mode -( http://web.barebones.com/ ). +( L<http://web.barebones.com/> ). =back =head2 Where can I get Perl macros for vi? For a complete version of Tom Christiansen's vi configuration file, -see http://www.cpan.org/authors/Tom_Christiansen/scripts/toms.exrc.gz , -the standard benchmark file for vi emulators. The file runs best with nvi, +see L<http://www.cpan.org/authors/Tom_Christiansen/scripts/toms.exrc.gz> , +the standard benchmark file for vi emulators. The file runs best with nvi, the current version of vi out of Berkeley, which incidentally can be built -with an embedded Perl interpreter--see http://www.cpan.org/src/misc/ . +with an embedded Perl interpreter--see L<http://www.cpan.org/src/misc/> . =head2 Where can I get perl-mode or cperl-mode for emacs? X<emacs> Since Emacs version 19 patchlevel 22 or so, there have been both a -perl-mode.el and support for the Perl debugger built in. These should +perl-mode.el and support for the Perl debugger built in. These should come with the standard Emacs 19 distribution. Note that the perl-mode of emacs will have fits with C<"main'foo"> -(single quote), and mess up the indentation and highlighting. You +(single quote), and mess up the indentation and highlighting. You are probably using C<"main::foo"> in new Perl code anyway, so this shouldn't be an issue. -For CPerlMode, see http://www.emacswiki.org/cgi-bin/wiki/CPerlMode +For CPerlMode, see L<http://www.emacswiki.org/cgi-bin/wiki/CPerlMode> =head2 How can I use curses with Perl? The Curses module from CPAN provides a dynamically loadable object -module interface to a curses library. A small demo can be found at the -directory http://www.cpan.org/authors/Tom_Christiansen/scripts/rep.gz ; +module interface to a curses library. A small demo can be found at the +directory L<http://www.cpan.org/authors/Tom_Christiansen/scripts/rep.gz> ; this program repeats a command and updates the screen as needed, rendering B<rep ps axu> similar to B<top>. @@ -567,7 +655,7 @@ simple gui. It hasn't been updated in a while. =item Wx This is a Perl binding for the cross-platform wxWidgets toolkit -( http://www.wxwidgets.org ). It works under Unix, Win32 and Mac OS X, +( L<http://www.wxwidgets.org> ). It works under Unix, Win32 and Mac OS X, using native widgets (Gtk under Unix). The interface follows the C++ interface closely, but the documentation is a little sparse for someone who doesn't know the library, mostly just referring you to the C++ @@ -575,7 +663,7 @@ documentation. =item Gtk and Gtk2 -These are Perl bindings for the Gtk toolkit ( http://www.gtk.org ). The +These are Perl bindings for the Gtk toolkit ( L<http://www.gtk.org> ). The interface changed significantly between versions 1 and 2 so they have separate Perl modules. It runs under Unix, Win32 and Mac OS X (currently it requires an X server on Mac OS, but a 'native' port is underway), and @@ -594,7 +682,7 @@ require familiarity with the C Win32 APIs, or reference to MSDN. =item CamelBones -CamelBones ( http://camelbones.sourceforge.net ) is a Perl interface to +CamelBones ( L<http://camelbones.sourceforge.net> ) is a Perl interface to Mac OS X's Cocoa GUI toolkit, and as such can be used to produce native GUIs on Mac OS X. It's not on CPAN, as it requires frameworks that CPAN.pm doesn't know how to install, but installation is via the @@ -616,59 +704,59 @@ again it appears not to be much used nowadays. =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. Jon Bentley's book +The best way to do this is to come up with a better algorithm. This +can often make a dramatic difference. Jon Bentley's book I<Programming Pearls> (that's not a misspelling!) has some good tips -on optimization, too. Advice on benchmarking boils down to: benchmark +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. You will probably want to +fails consider just buying faster hardware. You will probably want to read the answer to the earlier question "How do I profile my Perl programs?" if you haven't done so already. -A different approach is to autoload 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. 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 -write them in assembler. Similar to rewriting in C, modules that have +write them in assembler. Similar to rewriting in C, modules that have critical sections can be written in C (for instance, the PDL module from CPAN). 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 +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 it. See the F<INSTALL> file in the source distribution +thank you for it. See the F<INSTALL> file in the source distribution for more information. The undump program was an ancient attempt to speed up Perl program by -storing the already-compiled form to disk. This is no longer a viable +storing the already-compiled form to disk. This is no longer a viable option, as it only worked on a few architectures, and wasn't a good solution anyway. =head2 How can I make my Perl program take less memory? When it comes to time-space tradeoffs, Perl nearly always prefers to -throw memory at a problem. Scalars in Perl use more memory than -strings in C, arrays take more than that, and hashes use even more. While +throw memory at a problem. Scalars in Perl use more memory than +strings in C, arrays take more than that, and hashes use even more. While there's still a lot to be done, recent releases have been addressing -these issues. For example, as of 5.004, duplicate hash keys are +these issues. For example, as of 5.004, duplicate hash keys are shared amongst all hashes using them, so require no reallocation. In some cases, using substr() or vec() to simulate arrays can be -highly beneficial. For example, an array of a thousand booleans will +highly beneficial. For example, an array of a thousand booleans will take at least 20,000 bytes of space, but it can be turned into one -125-byte bit vector--a considerable memory savings. The standard +125-byte bit vector--a considerable memory savings. The standard Tie::SubstrHash module can also help for certain types of data -structure. If you're working with specialist data structures +structure. If you're working with specialist data structures (matrices, for instance) modules that implement these in C may use less memory than equivalent Perl modules. Another thing to try is learning whether your Perl was compiled with -the system malloc or with Perl's builtin malloc. Whichever one it +the system malloc or with Perl's builtin malloc. Whichever one it is, try using the other one and see whether this makes a difference. Information about malloc is in the F<INSTALL> file in the source -distribution. You can find out whether you are using perl's malloc by +distribution. You can find out whether you are using perl's malloc by typing C<perl -V:usemymalloc>. Of course, the best way to save memory is to not do anything to waste @@ -685,7 +773,7 @@ by line. Or more concretely, use a loop like this: # # Good Idea # - while (<FILE>) { + while (my $line = <$file_handle>) { # ... } @@ -694,7 +782,7 @@ instead of this: # # Bad Idea # - @data = <FILE>; + my @data = <$file_handle>; foreach (@data) { # ... } @@ -707,12 +795,12 @@ larger. Remember that both map and grep expect a LIST argument, so doing this: - @wanted = grep {/pattern/} <FILE>; + @wanted = grep {/pattern/} <$file_handle>; will cause the entire file to be slurped. For large files, it's better to loop: - while (<FILE>) { + while (<$file_handle>) { push(@wanted, $_) if /pattern/; } @@ -809,35 +897,41 @@ See also "How can I make my Perl program take less memory?" =head2 How can I make my CGI script more efficient? Beyond the normal measures described to make general Perl programs -faster or smaller, a CGI program has additional issues. It may be run -several times per second. Given that each time it runs it will need +faster or smaller, a CGI program has additional issues. It may be run +several times per second. Given that each time it runs it will need 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 +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 two popular ways to avoid this overhead. One solution +There are three 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 +L<http://www.apache.org/> ) with either of the mod_perl or mod_fastcgi 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 +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/ +anything a module written in C can. For more on mod_perl, see +L<http://perl.apache.org/> With the FCGI module (from CPAN) and the mod_fastcgi -module (available from http://www.fastcgi.com/ ) each of your Perl +module (available from L<http://www.fastcgi.com/> ) each of your Perl programs 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 programs, so investigate them with -care. +Finally, L<Plack> is a Perl module and toolkit that contains PSGI middleware, +helpers and adapters to web servers, allowing you to easily deploy scripts which +can continue running, and provides flexibility with regards to which web server +you use. It can allow existing CGI scripts to enjoy this flexibility and +performance with minimal changes, or can be used along with modern Perl web +frameworks to make writing and deploying web services with Perl a breeze. + +These solutions can have far-reaching effects on your system and on the way you +write your CGI programs, so investigate them with care. See also -http://www.cpan.org/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/ . +L<http://www.cpan.org/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/> . =head2 How can I hide the source for my Perl program? @@ -846,38 +940,38 @@ 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 +interpreted. (That doesn't mean that a CGI script's source is 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 +Some people regard this as a security problem. If your program does insecure things and relies on people not knowing how to exploit those -insecurities, it is not secure. It is often possible for someone to +insecurities, it is not secure. It is often possible for someone to determine the insecure things and exploit them without viewing the -source. Security through obscurity, the name for hiding your bugs +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 (Starting from Perl 5.8 the Filter::Simple and Filter::Util::Call modules are included in the standard distribution), but any decent programmer will be able to -decrypt it. You can try using the byte code compiler and interpreter +decrypt it. You can try using the byte code compiler and interpreter described later in L<perlfaq3>, but the curious might still be able to de-compile it. You can try using the native-code compiler described -later, but crackers might be able to disassemble it. These pose +later, but crackers might be able to disassemble it. These pose varying degrees of difficulty to people wanting to get at your code, but none can definitively conceal it (true of every language, not just Perl). -It is very easy to recover the source of Perl programs. You simply +It is very easy to recover the source of Perl programs. You simply feed the program to the perl interpreter and use the modules in -the B:: hierarchy. The B::Deparse module should be able to -defeat most attempts to hide source. Again, this is not +the B:: hierarchy. The B::Deparse module should be able to +defeat most attempts to hide source. Again, this is not unique to Perl. If you're concerned about people profiting from your code, then the bottom line is that nothing but a restrictive license will give you -legal security. License your software and pepper it with threatening +legal security. License your software and pepper it with threatening 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 @@ -887,27 +981,27 @@ you want to be sure your license's wording will stand up in court. (contributed by brian d foy) -In general, you can't do this. There are some things that may work -for your situation though. People usually ask this question +In general, you can't do this. There are some things that may work +for your situation though. People usually ask this question because they want to distribute their works without giving away the source code, and most solutions trade disk space for convenience. You probably won't see much of a speed increase either, since most solutions simply bundle a Perl interpreter in the final product (but see L<How can I make my Perl program run faster?>). -The Perl Archive Toolkit ( http://par.perl.org/ ) is Perl's -analog to Java's JAR. It's freely available and on CPAN ( -http://search.cpan.org/dist/PAR/ ). +The Perl Archive Toolkit ( L<http://par.perl.org/> ) is Perl's +analog to Java's JAR. It's freely available and on CPAN ( +L<http://search.cpan.org/dist/PAR/> ). There are also some commercial products that may work for you, although you have to buy a license for them. -The Perl Dev Kit ( http://www.activestate.com/Products/Perl_Dev_Kit/ ) +The Perl Dev Kit ( L<http://www.activestate.com/Products/Perl_Dev_Kit/> ) from ActiveState can "Turn your Perl programs into ready-to-run executables for HP-UX, Linux, Solaris and Windows." -Perl2Exe ( http://www.indigostar.com/perl2exe.htm ) is a command line -program for converting perl scripts to executable files. It targets both +Perl2Exe ( L<http://www.indigostar.com/perl2exe.htm> ) is a command line +program for converting perl scripts to executable files. It targets both Windows and Unix platforms. =head2 How can I get C<#!perl> to work on [MS-DOS,NT,...]? @@ -917,32 +1011,32 @@ For OS/2 just use extproc perl -S -your_switches as the first line in C<*.cmd> file (C<-S> due to a bug in cmd.exe's -"extproc" handling). For DOS one should first invent a corresponding +"extproc" handling). For DOS one should first invent a corresponding batch file and codify it in C<ALTERNATE_SHEBANG> (see the F<dosish.h> file in the source distribution for more information). 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, perhaps even building +perl interpreter. If you install another port, perhaps even building your own Win95/NT Perl from the standard sources by using a Windows port of gcc (e.g., with cygwin or mingw32), then you'll have to modify -the Registry yourself. In addition to associating C<.pl> with the +the Registry yourself. In addition to associating C<.pl> with the interpreter, NT people can use: C<SET PATHEXT=%PATHEXT%;.PL> to let them run the program C<install-linux.pl> merely by typing C<install-linux>. Under "Classic" MacOS, a perl program will have the appropriate Creator and Type, so that double-clicking them will invoke the MacPerl application. Under Mac OS X, clickable apps can be made from any C<#!> script using Wil -Sanchez' DropScript utility: http://www.wsanchez.net/software/ . +Sanchez' DropScript utility: L<http://www.wsanchez.net/software/> . I<IMPORTANT!>: Whatever you do, PLEASE don't get frustrated, and just throw the perl interpreter into your cgi-bin directory, in order to -get your programs working for a web server. This is an EXTREMELY big -security risk. Take the time to figure out how to do it correctly. +get your programs working for a web server. This is an EXTREMELY big +security risk. Take the time to figure out how to do it correctly. =head2 Can I write useful Perl programs on the command line? -Yes. Read L<perlrun> for more information. Some examples follow. +Yes. Read L<perlrun> for more information. Some examples follow. (These assume standard Unix shell quoting rules.) # sum first and last fields @@ -970,9 +1064,9 @@ OK, the last one was actually an Obfuscated Perl Contest entry. :-) The problem is usually that the command interpreters on those systems have rather different ideas about quoting than the Unix shells under -which the one-liners were created. On some systems, you may have to +which the one-liners were created. On some systems, you may have to change single-quotes to double ones, which you must I<NOT> do on Unix -or Plan9 systems. You might also have to change a single % to a %%. +or Plan9 systems. You might also have to change a single % to a %%. For example: @@ -993,13 +1087,13 @@ For example: perl -e "print ""Hello world\n""" The problem is that none of these examples are reliable: they depend on the -command interpreter. Under Unix, the first two often work. Under DOS, -it's entirely possible that neither works. If 4DOS was the command shell, +command interpreter. Under Unix, the first two often work. Under DOS, +it's entirely possible that 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>"" -Under the Mac, it depends which environment you are using. The MacPerl +Under the Mac, it depends which environment you are using. The MacPerl 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. @@ -1007,25 +1101,29 @@ characters as control characters. Using qq(), q(), and qx(), instead of "double quotes", 'single quotes', and `backticks`, may make one-liners easier to write. -There is no general solution to all of this. It is a mess. +There is no general solution to all of this. It is a mess. [Some of this answer was contributed by Kenneth Albanowski.] =head2 Where can I learn about CGI or Web programming in Perl? -For modules, get the CGI or LWP modules from CPAN. For textbooks, +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 +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 the troubleshooting guides and references in L<perlfaq9> or in the CGI MetaFAQ: - http://www.perl.org/CGI_MetaFAQ.html + L<http://www.perl.org/CGI_MetaFAQ.html> + +Looking in to L<Plack> and modern Perl web frameworks is highly recommended, +though; web programming in Perl has evolved a long way from the old days of +simple CGI scripts. =head2 Where can I learn about object-oriented Perl programming? -A good place to start is L<perlootut>, and you can use L<perlobj>, -for reference. +A good place to start is L<perltoot>, and you can use L<perlobj>, +L<perlboot>, L<perltoot>, L<perltooc>, and L<perlbot> for reference. A good book on OO on Perl is the "Object-Oriented Perl" by Damian Conway from Manning Publications, or "Intermediate Perl" @@ -1034,9 +1132,9 @@ by Randal Schwartz, brian d foy, and Tom Phoenix from O'Reilly Media. =head2 Where can I learn about linking C with Perl? If you want to call C from Perl, start with L<perlxstut>, -moving on to L<perlxs>, L<xsubpp>, and L<perlguts>. If you want to +moving on to L<perlxs>, L<xsubpp>, and L<perlguts>. If you want to call Perl from C, then read L<perlembed>, L<perlcall>, and -L<perlguts>. Don't forget that you can learn a lot from looking at +L<perlguts>. Don't forget that you can learn a lot from looking at how the authors of existing extension modules wrote their code and solved their problems. @@ -1048,8 +1146,8 @@ XS support files. =head2 I've read perlembed, perlguts, etc., but I can't embed perl in my C program; what am I doing wrong? -Download the ExtUtils::Embed kit from CPAN and run `make test'. If -the tests pass, read the pods again and again and again. If they +Download the ExtUtils::Embed kit from CPAN and run `make test'. If +the tests pass, read the pods again and again and again. If they fail, see L<perlbug> and send a bug report with the output of C<make test TEST_VERBOSE=1> along with C<perl -V>. @@ -1088,7 +1186,7 @@ This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. Irrespective of its distribution, all code examples here are in the public -domain. You are permitted and encouraged to use this code and any +domain. You are permitted and encouraged to use this code and any derivatives thereof in your own programs for fun or for profit as you -see fit. A simple comment in the code giving credit to the FAQ would +see fit. A simple comment in the code giving credit to the FAQ would be courteous but is not required. diff --git a/cpan/perlfaq/lib/perlfaq4.pod b/cpan/perlfaq/lib/perlfaq4.pod index 363f1176cb..7d431625fc 100644 --- a/cpan/perlfaq/lib/perlfaq4.pod +++ b/cpan/perlfaq/lib/perlfaq4.pod @@ -17,7 +17,7 @@ Scientist Should Know About Floating-Point Arithmetic" Internally, your computer represents floating-point numbers in binary. Digital (as in powers of two) computers cannot store all numbers -exactly. Some real numbers lose precision in the process. This is a +exactly. Some real numbers lose precision in the process. This is a problem with how computers store numbers and affects all computer languages, not just Perl. @@ -25,7 +25,7 @@ L<perlnumber> shows the gory details of number representations and conversions. To limit the number of decimal places in your numbers, you can use the -C<printf> or C<sprintf> function. See +C<printf> or C<sprintf> function. See L<perlop/"Floating-point Arithmetic"> for more details. printf "%.2f", 10/3; @@ -34,7 +34,7 @@ L<perlop/"Floating-point Arithmetic"> for more details. =head2 Why is int() broken? -Your C<int()> is most probably working just fine. It's the numbers that +Your C<int()> is most probably working just fine. It's the numbers that aren't quite what you think. First, see the answer to "Why am I getting long decimals @@ -47,7 +47,7 @@ For example, this will in most computers print 0, not 1, because even such simple numbers as 0.6 and 0.2 cannot be presented exactly by floating-point -numbers. What you think in the above as 'three' is really more like +numbers. What you think in the above as 'three' is really more like 2.9999999999999995559. =head2 Why isn't my octal data interpreted correctly? @@ -76,15 +76,15 @@ If you want to use the same literal digits (644) in Perl, you have to tell Perl to treat them as octal numbers either by prefixing the digits with a C<0> or using C<oct>: - chmod( 0644, $file); # right, has leading zero - chmod( oct(644), $file ); # also correct + chmod( 0644, $filename ); # right, has leading zero + chmod( oct(644), $filename ); # also correct The problem comes in when you take your numbers from something that Perl thinks is a string, such as a command line argument in C<@ARGV>: - chmod( $ARGV[0], $file); # wrong, even if "0644" + chmod( $ARGV[0], $filename ); # wrong, even if "0644" - chmod( oct($ARGV[0]), $file ); # correct, treat string as octal + chmod( oct($ARGV[0]), $filename ); # correct, treat string as octal You can always check the value you're using by printing it in octal notation to ensure it matches what you think it should be. Print it @@ -92,31 +92,31 @@ in octal and decimal format: printf "0%o %d", $number, $number; -=head2 Does Perl have a round() function? What about ceil() and floor()? Trig functions? +=head2 Does Perl have a round() function? What about ceil() and floor()? Trig functions? -Remember that C<int()> merely truncates toward 0. For rounding to a +Remember that C<int()> merely truncates toward 0. For rounding to a certain number of digits, C<sprintf()> or C<printf()> is usually the easiest route. printf("%.3f", 3.1415926535); # prints 3.142 -The Perltidy module (part of the standard Perl distribution) +The L<POSIX> module (part of the standard Perl distribution) implements C<ceil()>, C<floor()>, and a number of other mathematical and trigonometric functions. use POSIX; - $ceil = ceil(3.5); # 4 - $floor = floor(3.5); # 3 + my $ceil = ceil(3.5); # 4 + my $floor = floor(3.5); # 3 In 5.000 to 5.003 perls, trigonometry was done in the L<Math::Complex> -module. With 5.004, the L<Math::Trig> module (part of the standard Perl +module. With 5.004, the L<Math::Trig> module (part of the standard Perl distribution) implements the trigonometric functions. Internally it uses the L<Math::Complex> module and some functions can break out from the real axis into the complex plane, for example the inverse sine of 2. Rounding in financial applications can have serious implications, and -the rounding method used should be specified precisely. In these +the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system of rounding is being used by Perl, but instead to implement the rounding function you need yourself. @@ -124,21 +124,21 @@ need yourself. To see why, notice how you'll still have an issue on half-way-point alternation: - for ($i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i} + for (my $i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i} 0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7 0.8 0.8 0.9 0.9 1.0 1.0 -Don't blame Perl. It's the same as in C. IEEE says we have to do +Don't blame Perl. It's the same as in C. IEEE says we have to do this. Perl numbers whose absolute values are integers under 2**31 (on 32-bit machines) will work pretty much like mathematical integers. Other numbers are not guaranteed. =head2 How do I convert between numeric representations/bases/radixes? -As always with Perl there is more than one way to do it. Below are a +As always with Perl there is more than one way to do it. Below are a few examples of approaches to making common conversions between number -representations. This is intended to be representational rather than +representations. This is intended to be representational rather than exhaustive. Some of the examples later in L<perlfaq4> use the L<Bit::Vector> @@ -153,119 +153,119 @@ some programmers the notation might be familiar. Using perl's built in conversion of C<0x> notation: - $dec = 0xDEADBEEF; + my $dec = 0xDEADBEEF; Using the C<hex> function: - $dec = hex("DEADBEEF"); + my $dec = hex("DEADBEEF"); Using C<pack>: - $dec = unpack("N", pack("H8", substr("0" x 8 . "DEADBEEF", -8))); + my $dec = unpack("N", pack("H8", substr("0" x 8 . "DEADBEEF", -8))); Using the CPAN module C<Bit::Vector>: use Bit::Vector; - $vec = Bit::Vector->new_Hex(32, "DEADBEEF"); - $dec = $vec->to_Dec(); + my $vec = Bit::Vector->new_Hex(32, "DEADBEEF"); + my $dec = $vec->to_Dec(); =item How do I convert from decimal to hexadecimal Using C<sprintf>: - $hex = sprintf("%X", 3735928559); # upper case A-F - $hex = sprintf("%x", 3735928559); # lower case a-f + my $hex = sprintf("%X", 3735928559); # upper case A-F + my $hex = sprintf("%x", 3735928559); # lower case a-f Using C<unpack>: - $hex = unpack("H*", pack("N", 3735928559)); + my $hex = unpack("H*", pack("N", 3735928559)); Using L<Bit::Vector>: use Bit::Vector; - $vec = Bit::Vector->new_Dec(32, -559038737); - $hex = $vec->to_Hex(); + my $vec = Bit::Vector->new_Dec(32, -559038737); + my $hex = $vec->to_Hex(); And L<Bit::Vector> supports odd bit counts: use Bit::Vector; - $vec = Bit::Vector->new_Dec(33, 3735928559); + my $vec = Bit::Vector->new_Dec(33, 3735928559); $vec->Resize(32); # suppress leading 0 if unwanted - $hex = $vec->to_Hex(); + my $hex = $vec->to_Hex(); =item How do I convert from octal to decimal Using Perl's built in conversion of numbers with leading zeros: - $dec = 033653337357; # note the leading 0! + my $dec = 033653337357; # note the leading 0! Using the C<oct> function: - $dec = oct("33653337357"); + my $dec = oct("33653337357"); Using L<Bit::Vector>: use Bit::Vector; - $vec = Bit::Vector->new(32); + my $vec = Bit::Vector->new(32); $vec->Chunk_List_Store(3, split(//, reverse "33653337357")); - $dec = $vec->to_Dec(); + my $dec = $vec->to_Dec(); =item How do I convert from decimal to octal Using C<sprintf>: - $oct = sprintf("%o", 3735928559); + my $oct = sprintf("%o", 3735928559); Using L<Bit::Vector>: use Bit::Vector; - $vec = Bit::Vector->new_Dec(32, -559038737); - $oct = reverse join('', $vec->Chunk_List_Read(3)); + my $vec = Bit::Vector->new_Dec(32, -559038737); + my $oct = reverse join('', $vec->Chunk_List_Read(3)); =item How do I convert from binary to decimal Perl 5.6 lets you write binary numbers directly with the C<0b> notation: - $number = 0b10110110; + my $number = 0b10110110; Using C<oct>: my $input = "10110110"; - $decimal = oct( "0b$input" ); + my $decimal = oct( "0b$input" ); Using C<pack> and C<ord>: - $decimal = ord(pack('B8', '10110110')); + my $decimal = ord(pack('B8', '10110110')); Using C<pack> and C<unpack> for larger strings: - $int = unpack("N", pack("B32", + my $int = unpack("N", pack("B32", substr("0" x 32 . "11110101011011011111011101111", -32))); - $dec = sprintf("%d", $int); + my $dec = sprintf("%d", $int); # substr() is used to left-pad a 32-character string with zeros. Using L<Bit::Vector>: - $vec = Bit::Vector->new_Bin(32, "11011110101011011011111011101111"); - $dec = $vec->to_Dec(); + my $vec = Bit::Vector->new_Bin(32, "11011110101011011011111011101111"); + my $dec = $vec->to_Dec(); =item How do I convert from decimal to binary Using C<sprintf> (perl 5.6+): - $bin = sprintf("%b", 3735928559); + my $bin = sprintf("%b", 3735928559); Using C<unpack>: - $bin = unpack("B*", pack("N", 3735928559)); + my $bin = unpack("B*", pack("N", 3735928559)); Using L<Bit::Vector>: use Bit::Vector; - $vec = Bit::Vector->new_Dec(32, -559038737); - $bin = $vec->to_Bin(); + my $vec = Bit::Vector->new_Dec(32, -559038737); + my $bin = $vec->to_Bin(); The remaining transformations (e.g. hex -> oct, bin -> hex, etc.) are left as an exercise to the inclined reader. @@ -275,17 +275,17 @@ are left as an exercise to the inclined reader. =head2 Why doesn't & work the way I want it to? The behavior of binary arithmetic operators depends on whether they're -used on numbers or strings. The operators treat a string as a series +used on numbers or strings. The operators treat a string as a series of bits and work with that (the string C<"3"> is the bit pattern -C<00110011>). The operators work with the binary form of a number +C<00110011>). The operators work with the binary form of a number (the number C<3> is treated as the bit pattern C<00000011>). So, saying C<11 & 3> performs the "and" operation on numbers (yielding -C<3>). Saying C<"11" & "3"> performs the "and" operation on strings +C<3>). Saying C<"11" & "3"> performs the "and" operation on strings (yielding C<"1">). Most problems with C<&> and C<|> arise because the programmer thinks -they have a number but really it's a string or vice versa. To avoid this, +they have a number but really it's a string or vice versa. To avoid this, stringify the arguments explicitly (using C<""> or C<qq()>) or convert them to numbers explicitly (using C<0+$arg>). The rest arise because the programmer says: @@ -295,7 +295,7 @@ the programmer says: } but a string consisting of two null bytes (the result of C<"\020\020" -& "\101\101">) is not a false value in Perl. You need: +& "\101\101">) is not a false value in Perl. You need: if ( ("\020\020" & "\101\101") !~ /[^\000]/) { # ... @@ -311,29 +311,29 @@ or the L<PDL> extension (also available from CPAN). To call a function on each element in an array, and collect the results, use: - @results = map { my_func($_) } @array; + my @results = map { my_func($_) } @array; For example: - @triple = map { 3 * $_ } @single; + my @triple = map { 3 * $_ } @single; To call a function on each element of an array, but ignore the results: - foreach $iterator (@array) { + foreach my $iterator (@array) { some_func($iterator); } To call a function on each integer in a (small) range, you B<can> use: - @results = map { some_func($_) } (5 .. 25); + my @results = map { some_func($_) } (5 .. 25); but you should be aware that the C<..> operator creates a list of -all integers in the range. This can take a lot of memory for large -ranges. Instead use: +all integers in the range. This can take a lot of memory for large +ranges. Instead use: - @results = (); - for ($i=5; $i <= 500_005; $i++) { + my @results = (); + for (my $i=5; $i <= 500_005; $i++) { push(@results, some_func($i)); } @@ -357,24 +357,24 @@ once at the start of your program to seed the random number generator. BEGIN { srand() if $] < 5.004 } -5.004 and later automatically call C<srand> at the beginning. Don't +5.004 and later automatically call C<srand> at the beginning. Don't call C<srand> more than once--you make your numbers less random, rather than more. Computers are good at being predictable and bad at being random -(despite appearances caused by bugs in your programs :-). The +(despite appearances caused by bugs in your programs :-). The F<random> article in the "Far More Than You Ever Wanted To Know" collection in L<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz>, courtesy -of Tom Phoenix, talks more about this. John von Neumann said, "Anyone +of Tom Phoenix, talks more about this. John von Neumann said, "Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin." If you want numbers that are more random than C<rand> with C<srand> provides, you should also check out the L<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 L<http://www.nr.com/>. +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 the one that comes with your operating system, +look at "Numerical Recipes in C" at L<http://www.nr.com/>. =head2 How do I get a random number between X and Y? @@ -491,7 +491,7 @@ L<Date::Calc>, or L<DateTime> modules can help you. If it's a regular enough string that it always has the same format, you can split it up and pass the parts to C<timelocal> in the standard -L<Time::Local> module. Otherwise, you should look into the L<Date::Calc>, +L<Time::Local> module. Otherwise, you should look into the L<Date::Calc>, L<Date::Parse>, and L<Date::Manip> modules from CPAN. =head2 How can I find the Julian Day? @@ -524,9 +524,9 @@ You can also do the same things with the L<DateTime> module: $ perl -MDateTime -le'print DateTime->today->doy' 31 -You can use the L<Time::JulianDay> module available on CPAN. Ensure +You can use the L<Time::JulianDay> module available on CPAN. Ensure that you really want to find a Julian day, though, as many people have -different ideas about Julian days (see http://www.hermetic.ch/cal_stud/jdn.htm +different ideas about Julian days (see L<http://www.hermetic.ch/cal_stud/jdn.htm> for instance): $ perl -MTime::JulianDay -le 'print local_julian_day( time )' @@ -560,7 +560,7 @@ function. print "@date_time\n"; Most people try to use the time rather than the calendar to figure out -dates, but that assumes that days are twenty-four hours each. For +dates, but that assumes that days are twenty-four hours each. For most people, there are two days a year when they aren't: the switch to and from summer time throws this off. For example, the rest of the suggestions will be wrong sometimes: @@ -633,8 +633,8 @@ and L<Data::Validate::IP>. =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 (C<\>) +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; @@ -712,17 +712,17 @@ which also forces scalar context. =head2 How do I find matching/nesting anything? This isn't something that can be done in one regular expression, no -matter how complicated. To find something between two single +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. For balanced expressions using C<(>, C<{>, C<[> or +nested patterns. For balanced expressions using C<(>, C<{>, C<[> or C<< < >> as delimiters, use the CPAN module Regexp::Common, or see -L<perlre/(??{ code })>. For other cases, you'll have to write a +L<perlre/(??{ code })>. For other cases, 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 are +modules or oddities that will make your life a lot easier. There are the CPAN modules L<Parse::RecDescent>, L<Parse::Yapp>, and L<Text::Balanced>; and the C<byacc> program. Starting from perl 5.8 the L<Text::Balanced> is part of the standard distribution. @@ -735,7 +735,7 @@ pull out the smallest nesting parts one at a time: } A more complicated and sneaky approach is to make Perl's regular -expression engine do it for you. This is courtesy Dean Inada, and +expression engine do it for you. This is courtesy Dean Inada, and rather has the nature of an Obfuscated Perl Contest entry, but it really does work: @@ -754,7 +754,7 @@ really does work: Use C<reverse()> in scalar context, as documented in L<perlfunc/reverse>. - $reversed = reverse $string; + my $reversed = reverse $string; =head2 How do I expand tabs in a string? @@ -766,7 +766,7 @@ Or you can just use the L<Text::Tabs> module (part of the standard Perl distribution). use Text::Tabs; - @expanded_lines = expand(@lines_with_tabs); + my @expanded_lines = expand(@lines_with_tabs); =head2 How do I reformat a paragraph? @@ -776,9 +776,9 @@ Use L<Text::Wrap> (part of the standard Perl distribution): print wrap("\t", ' ', @paragraphs); The paragraphs you give to L<Text::Wrap> should not contain embedded -newlines. L<Text::Wrap> doesn't justify the lines (flush-right). +newlines. L<Text::Wrap> doesn't justify the lines (flush-right). -Or use the CPAN module L<Text::Autoformat>. Formatting files can be +Or use the CPAN module L<Text::Autoformat>. Formatting files can be easily done by making a shell alias, like so: alias fmt="perl -i -MText::Autoformat -n0777 \ @@ -794,8 +794,8 @@ To get the first character, for example, start at position 0 and grab the string of length 1. - $string = "Just another Perl Hacker"; - $first_char = substr( $string, 0, 1 ); # 'J' + my $string = "Just another Perl Hacker"; + my $first_char = substr( $string, 0, 1 ); # 'J' To change part of a string, you can use the optional fourth argument which is the replacement string. @@ -808,9 +808,9 @@ You can also use substr() as an lvalue. =head2 How do I change the Nth occurrence of something? -You have to keep track of N yourself. For example, let's say you want +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. These +C<"whosoever"> or C<"whomsoever">, case insensitively. These all assume that $_ contains the string to be altered. $count = 0; @@ -839,28 +839,29 @@ repetition count and repeated pattern like this: =head2 How can I count the number of occurrences of a substring within a string? -There are a number of ways, with varying efficiency. If you want a +There are a number of ways, with varying efficiency. If you want a count of a certain single character (X) within a string, you can use the C<tr///> function like so: - $string = "ThisXlineXhasXsomeXx'sXinXit"; - $count = ($string =~ tr/X//); + my $string = "ThisXlineXhasXsomeXx'sXinXit"; + my $count = ($string =~ tr/X//); print "There are $count X characters in the string"; -This is fine if you are just looking for a single character. However, +This is fine if you are just looking for a single character. However, if you are trying to count multiple character substrings within a -larger string, C<tr///> won't work. What you can do is wrap a while() -loop around a global pattern match. For example, let's count negative +larger string, C<tr///> won't work. What you can do is wrap a while() +loop around a global pattern match. For example, let's count negative integers: - $string = "-9 55 48 -2 23 -76 4 14 -44"; + my $string = "-9 55 48 -2 23 -76 4 14 -44"; + my $count = 0; while ($string =~ /-\d+/g) { $count++ } print "There are $count negative numbers in the string"; Another version uses a global match in list context, then assigns the result to a scalar, producing a count of the number of matches. - $count = () = $string =~ /-\d+/g; + my $count = () = $string =~ /-\d+/g; =head2 How do I capitalize all the words on one line? X<Text::Autoformat> X<capitalize> X<case, title> X<case, sentence> @@ -910,19 +911,19 @@ L<Text::CSV>, L<Text::CSV_XS>, and L<Text::ParseWords>, among others. Take the example case of trying to split a string that is comma-separated into its different fields. You can't use C<split(/,/)> -because you shouldn't split if the comma is inside quotes. For +because you shouldn't split if the comma is inside quotes. For example, take a data line like this: SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped" Due to the restriction of the quotes, this is a fairly complex -problem. Thankfully, we have Jeffrey Friedl, author of -I<Mastering Regular Expressions>, to handle these for us. He +problem. Thankfully, we have Jeffrey Friedl, author of +I<Mastering Regular Expressions>, to handle these for us. He suggests (assuming your string is contained in C<$text>): - @new = (); + my @new = (); push(@new, $+) while $text =~ m{ - "([^\"\\]*(?:\\.[^\"\\]*)*)",? # groups the phrase inside the quotes + "([^\"\\]*(?:\\.[^\"\\]*)*)",? # groups the phrase inside the quotes | ([^,]+),? | , }gx; @@ -938,6 +939,11 @@ Perl distribution) lets you say: use Text::ParseWords; @new = quotewords(",", 0, $text); +For parsing or generating CSV, though, using L<Text::CSV> rather than +implementing it yourself is highly recommended; you'll save yourself odd bugs +popping up later by just using code which has already been tried and tested in +production for years. + =head2 How do I strip blank space from the beginning/end of a string? (contributed by brian d foy) @@ -1002,29 +1008,29 @@ right with blanks and it will truncate the result to a maximum length of C<$pad_len>. # Left padding a string with blanks (no truncation): - $padded = sprintf("%${pad_len}s", $text); - $padded = sprintf("%*s", $pad_len, $text); # same thing + my $padded = sprintf("%${pad_len}s", $text); + my $padded = sprintf("%*s", $pad_len, $text); # same thing # Right padding a string with blanks (no truncation): - $padded = sprintf("%-${pad_len}s", $text); - $padded = sprintf("%-*s", $pad_len, $text); # same thing + my $padded = sprintf("%-${pad_len}s", $text); + my $padded = sprintf("%-*s", $pad_len, $text); # same thing # Left padding a number with 0 (no truncation): - $padded = sprintf("%0${pad_len}d", $num); - $padded = sprintf("%0*d", $pad_len, $num); # same thing + my $padded = sprintf("%0${pad_len}d", $num); + my $padded = sprintf("%0*d", $pad_len, $num); # same thing # Right padding a string with blanks using pack (will truncate): - $padded = pack("A$pad_len",$text); + my $padded = pack("A$pad_len",$text); If you need to pad with a character other than blank or zero you can use -one of the following methods. They all generate a pad string with the +one of the following methods. They all generate a pad string with the C<x> operator and combine that with C<$text>. These methods do not truncate C<$text>. Left and right padding with any character, creating a new string: - $padded = $pad_char x ( $pad_len - length( $text ) ) . $text; - $padded = $text . $pad_char x ( $pad_len - length( $text ) ); + my $padded = $pad_char x ( $pad_len - length( $text ) ) . $text; + my $padded = $text . $pad_char x ( $pad_len - length( $text ) ); Left and right padding with any character, modifying C<$text> directly: @@ -1095,7 +1101,7 @@ to their variable's values: $string = 'Say hello to $foo and $bar'; One way I can do this involves the substitution operator and a double -C</e> flag. The first C</e> evaluates C<$1> on the replacement side and +C</e> flag. The first C</e> evaluates C<$1> on the replacement side and turns it into C<$foo>. The second /e starts with C<$foo> and replaces it with its value. C<$foo>, then, turns into 'Fred', and that's finally what's left in the string: @@ -1132,21 +1138,21 @@ signal that I missed something: The problem is that those double-quotes force stringification--coercing numbers and references into strings--even -when you don't want them to be strings. Think of it this way: -double-quote expansion is used to produce new strings. If you already +when you don't want them to be strings. Think of it this way: +double-quote expansion is used to produce new strings. If you already have a string, why do you need more? If you get used to writing odd things like these: print "$var"; # BAD - $new = "$old"; # BAD + my $new = "$old"; # BAD somefunc("$var"); # BAD -You'll be in trouble. Those should (in 99.8% of the cases) be +You'll be in trouble. Those should (in 99.8% of the cases) be the simpler and more direct: print $var; - $new = $old; + my $new = $old; somefunc($var); Otherwise, besides slowing you down, you're going to break code when @@ -1166,7 +1172,7 @@ syscall() function. Stringification also destroys arrays. - @lines = `command`; + my @lines = `command`; print "@lines"; # WRONG - extra blanks print @lines; # right @@ -1190,7 +1196,7 @@ If you want to indent the text in the here document, you can do this: # all in one - ($VAR = <<HERE_TARGET) =~ s/^\s+//gm; + (my $VAR = <<HERE_TARGET) =~ s/^\s+//gm; your text goes here HERE_TARGET @@ -1199,18 +1205,18 @@ But the HERE_TARGET must still be flush against the margin. If you want that indented also, you'll have to quote in the indentation. - ($quote = <<' FINIS') =~ s/^\s+//gm; + (my $quote = <<' FINIS') =~ s/^\s+//gm; ...we will have peace, when you and all your works have perished--and the works of your dark master to whom you would deliver us. You are a liar, Saruman, and a corrupter - of men's hearts. --Theoden in /usr/src/perl/taint.c + of men's hearts. --Theoden in /usr/src/perl/taint.c FINIS $quote =~ s/\s+--/\n--/; A nice general-purpose fixer-upper function for indented here documents -follows. It expects to be called with a here document as its argument. +follows. It expects to be called with a here document as its argument. It looks to see whether each line begins with a common substring, and -if so, strips that substring off. Otherwise, it takes the amount of leading +if so, strips that substring off. Otherwise, it takes the amount of leading whitespace found on the first line and removes that much off each subsequent line. @@ -1228,7 +1234,7 @@ subsequent line. This works with leading special strings, dynamically determined: - $remember_the_main = fix<<' MAIN_INTERPRETER_LOOP'; + my $remember_the_main = fix<<' MAIN_INTERPRETER_LOOP'; @@@ int @@@ runops() { @@@ SAVEI32(runlevel); @@ -1242,7 +1248,7 @@ This works with leading special strings, dynamically determined: Or with a fixed amount of leading whitespace, with remaining indentation correctly preserved: - $poem = fix<<EVER_ON_AND_ON; + my $poem = fix<<EVER_ON_AND_ON; Now far ahead the Road has gone, And I must follow, if I can, Pursuing it with eager feet, @@ -1423,10 +1429,10 @@ same thing. (portions of this answer contributed by Anno Siegel and brian d foy) Hearing the word "in" is an I<in>dication that you probably should have -used a hash, not a list or array, to store your data. Hashes are -designed to answer this question quickly and efficiently. Arrays aren't. +used a hash, not a list or array, to store your data. Hashes are +designed to answer this question quickly and efficiently. Arrays aren't. -That being said, there are several ways to approach this. In Perl 5.10 +That being said, there are several ways to approach this. In Perl 5.10 and later, you can use the smart match operator to check that an item is contained in an array or a hash: @@ -1445,18 +1451,18 @@ are going to make this query many times over arbitrary string values, the fastest way is probably to invert the original array and maintain a hash whose keys are the first array's values: - @blues = qw/azure cerulean teal turquoise lapis-lazuli/; - %is_blue = (); + my @blues = qw/azure cerulean teal turquoise lapis-lazuli/; + my %is_blue = (); for (@blues) { $is_blue{$_} = 1 } -Now you can check whether C<$is_blue{$some_color}>. It might have +Now you can check whether C<$is_blue{$some_color}>. It might have been a good idea to keep the blues all in a hash in the first place. If the values are all small integers, you could use a simple indexed -array. This kind of an array will take up less space: +array. This kind of an array will take up less space: - @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31); - @is_tiny_prime = (); + my @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31); + my @is_tiny_prime = (); for (@primes) { $is_tiny_prime[$_] = 1 } # or simply @istiny_prime[@primes] = (1) x @primes; @@ -1465,18 +1471,18 @@ Now you check whether $is_tiny_prime[$some_number]. If the values in question are integers instead of strings, you can save quite a lot of space by using bit strings instead: - @articles = ( 1..10, 150..2000, 2017 ); + my @articles = ( 1..10, 150..2000, 2017 ); undef $read; for (@articles) { vec($read,$_,1) = 1 } Now check whether C<vec($read,$n,1)> is true for some C<$n>. These methods guarantee fast individual tests but require a re-organization -of the original list or array. They only pay off if you have to test +of the original list or array. They only pay off if you have to test multiple values against the same array. If you are testing only once, the standard module L<List::Util> exports -the function C<first> for this purpose. It works by stopping once it +the function C<first> for this purpose. It works by stopping once it finds the element. It's written in C for speed, and its Perl equivalent looks like this subroutine: @@ -1500,21 +1506,21 @@ list context. my @matches = grep $_ eq $whatever, @array; -=head2 How do I compute the difference of two arrays? How do I compute the intersection of two arrays? +=head2 How do I compute the difference of two arrays? How do I compute the intersection of two arrays? -Use a hash. Here's code to do both and more. It assumes that each +Use a hash. Here's code to do both and more. It assumes that each element is unique in a given array: - @union = @intersection = @difference = (); - %count = (); - foreach $element (@array1, @array2) { $count{$element}++ } - foreach $element (keys %count) { + my (@union, @intersection, @difference); + my %count = (); + foreach my $element (@array1, @array2) { $count{$element}++ } + foreach my $element (keys %count) { push @union, $element; push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element; } Note that this is the I<symmetric difference>, that is, all elements -in either A or in B but not in both. Think of it as an xor operation. +in either A or in B but not in both. Think of it as an xor operation. =head2 How do I test whether two arrays or hashes are equal? @@ -1531,9 +1537,9 @@ with the least amount of work: say "The hash keys are the same"; } -The following code works for single-level arrays. It uses a +The following code works for single-level arrays. It uses a stringwise comparison, and does not distinguish defined versus -undefined empty strings. Modify if you have other needs. +undefined empty strings. Modify if you have other needs. $are_equal = compare_arrays(\@frogs, \@toads); @@ -1548,22 +1554,22 @@ undefined empty strings. Modify if you have other needs. } For multilevel structures, you may wish to use an approach more -like this one. It uses the CPAN module L<FreezeThaw>: +like this one. It uses the CPAN module L<FreezeThaw>: use FreezeThaw qw(cmpStr); - @a = @b = ( "this", "that", [ "more", "stuff" ] ); + my @a = my @b = ( "this", "that", [ "more", "stuff" ] ); printf "a and b contain %s arrays\n", cmpStr(\@a, \@b) == 0 ? "the same" : "different"; -This approach also works for comparing hashes. Here we'll demonstrate +This approach also works for comparing hashes. Here we'll demonstrate two different answers: use FreezeThaw qw(cmpStr cmpStrHard); - %a = %b = ( "this" => "that", "extra" => [ "more", "stuff" ] ); + my %a = my %b = ( "this" => "that", "extra" => [ "more", "stuff" ] ); $a{EXTRA} = \%b; $b{EXTRA} = \%a; @@ -1575,7 +1581,7 @@ two different answers: The first reports that both those the hashes contain the same data, -while the second reports that they do not. Which you prefer is left as +while the second reports that they do not. Which you prefer is left as an exercise to the reader. =head2 How do I find the first array element for which a condition is true? @@ -1590,7 +1596,7 @@ with Perl 5.8. This example finds the first element that contains my $element = first { /Perl/ } @array; If you cannot use L<List::Util>, you can make your own loop to do the -same thing. Once you find the element, you stop the loop with last. +same thing. Once you find the element, you stop the loop with last. my $found; foreach ( @array ) { @@ -1627,7 +1633,7 @@ reallocate less memory, or quickly insert elements in the middle of the chain. Steve Lembark goes through the details in his YAPC::NA 2009 talk "Perly -Linked Lists" ( http://www.slideshare.net/lembark/perly-linked-lists ), +Linked Lists" ( L<http://www.slideshare.net/lembark/perly-linked-lists> ), although you can just use his L<LinkedList::Single> module. =head2 How do I handle circular lists? @@ -1729,7 +1735,8 @@ Use C<for>/C<foreach>: Here's another; let's compute spherical volumes: - for (@volumes = @radii) { # @volumes has changed parts + my @volumes = @radii; + for (@volumes) { # @volumes has changed parts $_ **= 3; $_ *= (4/3) * 3.14159; # this will be constant folded } @@ -1737,14 +1744,14 @@ Here's another; let's compute spherical volumes: which can also be done with C<map()> which is made to transform one list into another: - @volumes = map {$_ ** 3 * (4/3) * 3.14159} @radii; + my @volumes = map {$_ ** 3 * (4/3) * 3.14159} @radii; If you want to do the same thing to modify the values of the -hash, you can use the C<values> function. As of Perl 5.6 +hash, you can use the C<values> function. As of Perl 5.6 the values are not copied, so if you modify $orbit (in this case), you modify the value. - for $orbit ( values %orbits ) { + for my $orbit ( values %orbits ) { ($orbit **= 3) *= (4/3) * 3.14159; } @@ -1757,8 +1764,8 @@ the hash is to be modified. Use the C<rand()> function (see L<perlfunc/rand>): - $index = rand @array; - $element = $array[$index]; + my $index = rand @array; + my $element = $array[$index]; Or, simply: @@ -1836,33 +1843,34 @@ Supply a comparison function to sort() (described in L<perlfunc/sort>): @list = sort { $a <=> $b } @list; The default sort function is cmp, string comparison, which would -sort C<(1, 2, 10)> into C<(1, 10, 2)>. C<< <=> >>, used above, is +sort C<(1, 2, 10)> into C<(1, 10, 2)>. C<< <=> >>, used above, is the numerical comparison operator. If you have a complicated function needed to pull out the part you -want to sort on, then don't do it inside the sort function. Pull it +want to sort on, then don't do it inside the sort function. Pull it out first, because the sort BLOCK can be called many times for the -same element. Here's an example of how to pull out the first word +same element. Here's an example of how to pull out the first word after the first number on each item, and then sort those words case-insensitively. - @idx = (); + my @idx; for (@data) { + my $item; ($item) = /\d+\s*(\S+)/; push @idx, uc($item); } - @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ]; + my @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ]; which could also be written this way, using a trick that's come to be known as the Schwartzian Transform: - @sorted = map { $_->[0] } + my @sorted = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [ $_, uc( (/\d+\s*(\S+)/)[0]) ] } @data; If you need to sort on several fields, the following paradigm is useful. - @sorted = sort { + my @sorted = sort { field1($a) <=> field1($b) || field2($a) cmp field2($b) || field3($a) cmp field3($b) @@ -1872,7 +1880,7 @@ This can be conveniently combined with precalculation of keys as given above. See the F<sort> article in the "Far More Than You Ever Wanted -To Know" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz for +To Know" collection in L<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> for more about this approach. See also the question later in L<perlfaq4> on sorting hashes. @@ -1887,8 +1895,8 @@ For example, you don't have to store individual bits in an array array of bits to a string, use C<vec()> to set the right bits. This sets C<$vec> to have bit N set only if C<$ints[N]> was set: - @ints = (...); # array of bits, e.g. ( 1, 0, 0, 1, 1, 0 ... ) - $vec = ''; + my @ints = (...); # array of bits, e.g. ( 1, 0, 0, 1, 1, 0 ... ) + my $vec = ''; foreach( 0 .. $#ints ) { vec($vec,$_,1) = 1 if $ints[$_]; } @@ -1944,9 +1952,9 @@ from Benjamin Goldberg: Or use the CPAN module L<Bit::Vector>: - $vector = Bit::Vector->new($num_of_bits); + my $vector = Bit::Vector->new($num_of_bits); $vector->Index_List_Store(@ints); - @ints = $vector->Index_List_Read(); + my @ints = $vector->Index_List_Read(); L<Bit::Vector> provides efficient methods for bit vector, sets of small integers and "big int" math. @@ -1954,10 +1962,10 @@ small integers and "big int" math. Here's a more extensive illustration using vec(): # vec demo - $vector = "\xff\x0f\xef\xfe"; + my $vector = "\xff\x0f\xef\xfe"; print "Ilya's string \\xff\\x0f\\xef\\xfe represents the number ", unpack("N", $vector), "\n"; - $is_set = vec($vector, 23, 1); + my $is_set = vec($vector, 23, 1); print "Its 23rd bit is ", $is_set ? "set" : "clear", ".\n"; pvec($vector); @@ -1997,7 +2005,7 @@ Here's a more extensive illustration using vec(): =head2 Why does defined() return true on empty arrays and hashes? The short story is that you should probably only use defined on scalars or -functions, not on aggregates (arrays and hashes). See L<perlfunc/defined> +functions, not on aggregates (arrays and hashes). See L<perlfunc/defined> in the 5.004 release or later of Perl for more detail. =head1 Data: Hashes (Associative Arrays) @@ -2113,30 +2121,30 @@ from C<%hash2> replace values from C<%hash1> when they have keys in common: The easy answer is "Don't do that!" If you iterate through the hash with each(), you can delete the key -most recently returned without worrying about it. If you delete or add +most recently returned without worrying about it. If you delete or add other keys, the iterator may skip or double up on them since perl -may rearrange the hash table. See the +may rearrange the hash table. See the entry for C<each()> in L<perlfunc>. =head2 How do I look up a hash element by value? Create a reverse hash: - %by_value = reverse %by_key; - $key = $by_value{$value}; + my %by_value = reverse %by_key; + my $key = $by_value{$value}; -That's not particularly efficient. It would be more space-efficient +That's not particularly efficient. It would be more space-efficient to use: - while (($key, $value) = each %by_key) { + while (my ($key, $value) = each %by_key) { $by_value{$value} = $key; } If your hash could have repeated values, the methods above will only find -one of the associated keys. This may or may not worry you. If it does +one of the associated keys. This may or may not worry you. If it does worry you, you can always reverse the hash into a hash of arrays instead: - while (($key, $value) = each %by_key) { + while (my ($key, $value) = each %by_key) { push @{$key_list_by_value{$value}}, $key; } @@ -2193,11 +2201,9 @@ comparing the keys, we can compute a value with them and use that value as the comparison. For instance, to make our report order case-insensitive, we use -the C<\L> sequence in a double-quoted string to make everything -lowercase. The C<sort()> block then compares the lowercased -values to determine in which order to put the keys. +C<lc> to lowercase the keys before comparing them: - my @keys = sort { "\L$a" cmp "\L$b" } keys %hash; + my @keys = sort { lc $a cmp lc $b } keys %hash; Note: if the computation is expensive or the hash has many elements, you may want to look at the Schwartzian Transform to cache the @@ -2231,16 +2237,16 @@ need to do this? :) =head2 What's the difference between "delete" and "undef" with hashes? Hashes contain pairs of scalars: the first is the key, the -second is the value. The key will be coerced to a string, +second is the value. The key will be coerced to a string, although the value can be any kind of scalar: string, -number, or reference. If a key C<$key> is present in -%hash, C<exists($hash{$key})> will return true. The value +number, or reference. If a key C<$key> is present in +%hash, C<exists($hash{$key})> will return true. The value for a given key can be C<undef>, in which case C<$hash{$key}> will be C<undef> while C<exists $hash{$key}> -will return true. This corresponds to (C<$key>, C<undef>) +will return true. This corresponds to (C<$key>, C<undef>) being in the hash. -Pictures help... Here's the C<%hash> table: +Pictures help... Here's the C<%hash> table: keys values +------+------+ @@ -2333,28 +2339,28 @@ See the documentation for C<each> in L<perlfunc>. =head2 How can I get the unique keys from two hashes? First you extract the keys from the hashes into lists, then solve -the "removing duplicates" problem described above. For example: +the "removing duplicates" problem described above. For example: - %seen = (); - for $element (keys(%foo), keys(%bar)) { + my %seen = (); + for my $element (keys(%foo), keys(%bar)) { $seen{$element}++; } - @uniq = keys %seen; + my @uniq = keys %seen; Or more succinctly: - @uniq = keys %{{%foo,%bar}}; + my @uniq = keys %{{%foo,%bar}}; Or if you really want to save space: - %seen = (); + my %seen = (); while (defined ($key = each %foo)) { $seen{$key}++; } while (defined ($key = each %bar)) { $seen{$key}++; } - @uniq = keys %seen; + my @uniq = keys %seen; =head2 How can I store a multidimensional array in a DBM file? @@ -2434,8 +2440,8 @@ Usually a hash ref, perhaps like this: References are documented in L<perlref> and L<perlreftut>. Examples of complex data structures are given in L<perldsc> and -L<perllol>. Examples of structures and object-oriented classes are -in L<perlootut>. +L<perllol>. Examples of structures and object-oriented classes are +in L<perltoot>. =head2 How can I use a reference as a hash key? @@ -2546,7 +2552,7 @@ Also see L<perlfunc/"binmode"> or L<perlopentut>. If you're concerned about 8-bit textual data then see L<perllocale>. If you want to deal with multibyte characters, however, there are -some gotchas. See the section on Regular Expressions. +some gotchas. See the section on Regular Expressions. =head2 How do I determine whether a scalar is a number/whole/integer/float? @@ -2610,9 +2616,9 @@ instead. =head2 How do I keep persistent data across program calls? For some specific applications, you can use one of the DBM modules. -See L<AnyDBM_File>. More generically, you should consult the L<FreezeThaw> -or L<Storable> modules from CPAN. Starting from Perl 5.8 L<Storable> is part -of the standard distribution. Here's one example using L<Storable>'s C<store> +See L<AnyDBM_File>. More generically, you should consult the L<FreezeThaw> +or L<Storable> modules from CPAN. Starting from Perl 5.8, L<Storable> is part +of the standard distribution. Here's one example using L<Storable>'s C<store> and C<retrieve> functions: use Storable; @@ -2625,7 +2631,7 @@ and C<retrieve> functions: =head2 How do I print out or copy a recursive data structure? The L<Data::Dumper> module on CPAN (or the 5.005 release of Perl) is great -for printing out data structures. The L<Storable> module on CPAN (or the +for printing out data structures. The L<Storable> module on CPAN (or the 5.8 release of Perl), provides a function called C<dclone> that recursively copies its argument. @@ -2633,7 +2639,7 @@ copies its argument. $r2 = dclone($r1); Where C<$r1> can be a reference to any kind of data structure you'd like. -It will be deeply copied. Because C<dclone> takes and returns references, +It will be deeply copied. Because C<dclone> takes and returns references, you'd have to add extra punctuation if you had a hash of arrays that you wanted to copy. @@ -2671,7 +2677,7 @@ This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. Irrespective of its distribution, all code examples in this file -are hereby placed into the public domain. You are permitted and +are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun -or for profit as you see fit. A simple comment in the code giving +or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required. diff --git a/cpan/perlfaq/lib/perlfaq5.pod b/cpan/perlfaq/lib/perlfaq5.pod index 011e2e1ce2..325b2cc060 100644 --- a/cpan/perlfaq/lib/perlfaq5.pod +++ b/cpan/perlfaq/lib/perlfaq5.pod @@ -7,13 +7,13 @@ perlfaq5 - Files and Formats This section deals with I/O and the "f" issues: filehandles, flushing, formats, and footers. -=head2 How do I flush/unbuffer an output filehandle? Why must I do this? +=head2 How do I flush/unbuffer an output filehandle? Why must I do this? X<flush> X<buffer> X<unbuffer> X<autoflush> (contributed by brian d foy) You might like to read Mark Jason Dominus's "Suffering From Buffering" -at http://perl.plover.com/FAQs/Buffering.html . +at L<http://perl.plover.com/FAQs/Buffering.html> . Perl normally buffers output so it doesn't make a system call for every bit of output. By saving up output, it makes fewer expensive system calls. @@ -488,7 +488,7 @@ Storing the keys in an array makes it easy to operate on them as a group or loop over them with C<for>. It also avoids polluting the program with global variables and using symbolic references. -=head2 How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles? +=head2 How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles? X<filehandle, local> X<filehandle, passing> X<filehandle, reference> As of perl5.6, open() autovivifies file and directory handles @@ -1190,7 +1190,7 @@ C<"\n\n"> to accept empty paragraphs. Note that a blank line must have no blanks in it. Thus S<C<"fred\n \nstuff\n\n">> is one paragraph, but C<"fred\n\nstuff\n\n"> is two. -=head2 How can I read a single character from a file? From the keyboard? +=head2 How can I read a single character from a file? From the keyboard? X<getc> X<file, reading one character at a time> You can use the builtin C<getc()> function for most filehandles, but @@ -1396,7 +1396,7 @@ Or, just use the fdopen(3S) feature of C<open()>: close $fh; } -=head2 Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work? +=head2 Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work? X<filename, DOS issues> Whoops! You just put a tab and a formfeed into that filename! @@ -1422,11 +1422,11 @@ files. This makes glob() portable even to legacy systems. Your port may include proprietary globbing functions as well. Check its documentation for details. -=head2 Why does Perl let me delete read-only files? Why does C<-i> clobber protected files? Isn't this a bug in Perl? +=head2 Why does Perl let me delete read-only files? Why does C<-i> clobber protected files? Isn't this a bug in Perl? This is elaborately and painstakingly described in the F<file-dir-perms> article in the "Far More Than You Ever Wanted To -Know" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz . +Know" collection in L<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> . The executive summary: learn how your filesystem works. The permissions on a file say what can happen to the data in that file. diff --git a/cpan/perlfaq/lib/perlfaq6.pod b/cpan/perlfaq/lib/perlfaq6.pod index 7327b68d95..e60d1dfd71 100644 --- a/cpan/perlfaq/lib/perlfaq6.pod +++ b/cpan/perlfaq/lib/perlfaq6.pod @@ -6,7 +6,7 @@ perlfaq6 - Regular Expressions This section is surprisingly small because the rest of the FAQ is littered with answers involving regular expressions. For example, -decoding a URL and checking whether something is a number are handled +decoding a URL and checking whether something is a number can be handled with regular expressions, but those answers are found elsewhere in this document (in L<perlfaq9>: "How do I decode or create those %-encodings on the web" and L<perlfaq4>: "How do I determine whether a scalar is @@ -68,6 +68,10 @@ delimiter within the pattern: s/\/usr\/local/\/usr\/share/g; # bad delimiter choice s#/usr/local#/usr/share#g; # better +Using logically paired delimiters can be even more readable: + + s{/usr/local/}{/usr/share}g; # better still + =back =head2 I'm having trouble matching over more than one line. What's wrong? @@ -159,7 +163,7 @@ If you just want to get work done, use a module and forget about the regular expressions. The L<XML::Parser> and L<HTML::Parser> modules are good starts, although each namespace has other parsing modules specialized for certain tasks and different ways of doing it. Start at -CPAN Search ( http://search.cpan.org ) and wonder at all the work people +CPAN Search ( L<http://search.cpan.org> ) and wonder at all the work people have done for you already! :) The problem with things such as XML is that they have balanced text @@ -1049,7 +1053,7 @@ but this usually can be worked around. =head2 How do I match a regular expression that's in a variable? X<regex, in variable> X<eval> X<regex> X<quotemeta> X<\Q, regex> -X<\E, regex>, X<qr//> +X<\E, regex> X<qr//> (contributed by brian d foy) diff --git a/cpan/perlfaq/lib/perlfaq7.pod b/cpan/perlfaq/lib/perlfaq7.pod index 38329b229e..96c621a31d 100644 --- a/cpan/perlfaq/lib/perlfaq7.pod +++ b/cpan/perlfaq/lib/perlfaq7.pod @@ -10,7 +10,7 @@ clearly fit into any of the other sections. =head2 Can I get a BNF/yacc/RE for the Perl language? There is no BNF, but you can paw your way through the yacc grammar in -perly.y in the source distribution if you're particularly brave. The +perly.y in the source distribution if you're particularly brave. The grammar relies on very smart tokenizing code, so be prepared to venture into toke.c as well. @@ -26,7 +26,7 @@ They are type specifiers, as detailed in L<perldata>: @ for arrays % for hashes (associative arrays) & for subroutines (aka functions, procedures, methods) - * for all types of that symbol name. In version 4 you used them like + * for all types of that symbol name. In version 4 you used them like pointers, but in modern perls you can just use references. There are a couple of other symbols that @@ -37,18 +37,18 @@ really type specifiers: \ takes a reference to something. Note that <FILE> is I<neither> the type specifier for files -nor the name of the handle. It is the C<< <> >> operator applied -to the handle FILE. It reads one line (well, record--see +nor the name of the handle. It is the C<< <> >> operator applied +to the handle FILE. It reads one line (well, record--see L<perlvar/$E<sol>>) from the handle FILE in scalar context, or I<all> lines -in list context. When performing open, close, or any other operation +in list context. When performing open, close, or any other operation besides C<< <> >> on files, or even when talking about the handle, do -I<not> use the brackets. These are correct: C<eof(FH)>, C<seek(FH, 0, +I<not> use the brackets. These are correct: C<eof(FH)>, C<seek(FH, 0, 2)> and "copying from STDIN to FILE". =head2 Do I always/never have to quote my strings or use semicolons and commas? Normally, a bareword doesn't need to be quoted, but in most cases -probably should be (and must be under C<use strict>). But a hash key +probably should be (and must be under C<use strict>). But a hash key consisting of a simple word and the left-hand operand to the C<< => >> operator both count as though they were quoted: @@ -59,7 +59,7 @@ count as though they were quoted: bar => stuff 'bar' => stuff The final semicolon in a block is optional, as is the final comma in a -list. Good style (see L<perlstyle>) says to put them in except for +list. Good style (see L<perlstyle>) says to put them in except for one-liners: if ($whoops) { exit 1 } @@ -102,7 +102,7 @@ See L<perllexwarn> for more details. Additionally, you can enable and disable categories of warnings. You turn off the categories you want to ignore and you can still -get other categories of warnings. See L<perllexwarn> for the +get other categories of warnings. See L<perllexwarn> for the complete details, including the category names and hierarchy. { @@ -123,15 +123,15 @@ use my() on C<$^W>, only local(). =head2 What's an extension? -An extension is a way of calling compiled C code from Perl. Reading +An extension is a way of calling compiled C code from Perl. Reading L<perlxstut> is a good place to learn more about extensions. =head2 Why do Perl operators have different precedence than C operators? -Actually, they don't. All C operators that Perl copies have the same -precedence in Perl as they do in C. The problem is with operators that C +Actually, they don't. All C operators that Perl copies have the same +precedence in Perl as they do in C. The problem is with operators that C doesn't have, especially functions that give a list context to everything -on their right, eg. print, chmod, exec, and so on. Such functions are +on their right, eg. print, chmod, exec, and so on. Such functions are called "list operators" and appear as such in the precedence table in L<perlop>. @@ -153,28 +153,28 @@ The "English" operators (C<and>, C<or>, C<xor>, and C<not>) deliberately have precedence lower than that of list operators for just such situations as the one above. -Another operator with surprising precedence is exponentiation. It +Another operator with surprising precedence is exponentiation. It binds more tightly even than unary minus, making C<-2**2> produce a -negative not a positive four. It is also right-associating, meaning +negative not a positive four. It is also right-associating, meaning that C<2**3**2> is two raised to the ninth power, not eight squared. Although it has the same precedence as in C, Perl's C<?:> operator -produces an lvalue. This assigns $x to either $a or $b, depending +produces an lvalue. This assigns $x to either $a or $b, depending on the trueness of $maybe: ($maybe ? $a : $b) = $x; =head2 How do I declare/create a structure? -In general, you don't "declare" a structure. Just use a (probably -anonymous) hash reference. See L<perlref> and L<perldsc> for details. +In general, you don't "declare" a structure. Just use a (probably +anonymous) hash reference. See L<perlref> and L<perldsc> for details. Here's an example: $person = {}; # new anonymous hash $person->{AGE} = 24; # set field AGE to 24 $person->{NAME} = "Nat"; # set field NAME to "Nat" -If you're looking for something a bit more rigorous, try L<perlootut>. +If you're looking for something a bit more rigorous, try L<perltoot>. =head2 How do I create a module? @@ -186,16 +186,16 @@ overview of the process along with a couple of suggestions about style. If you need to include C code or C library interfaces in -your module, you'll need h2xs. h2xs will create the module +your module, you'll need h2xs. h2xs will create the module distribution structure and the initial interface files -you'll need. L<perlxs> and L<perlxstut> explain the details. +you'll need. L<perlxs> and L<perlxstut> explain the details. If you don't need to use C code, other tools such as ExtUtils::ModuleMaker and Module::Starter, can help you create a skeleton module distribution. You may also want to see Sam Tregar's "Writing Perl Modules -for CPAN" ( http://apress.com/book/bookDisplay.html?bID=14 ) +for CPAN" ( L<http://apress.com/book/bookDisplay.html?bID=14> ) which is the best hands-on guide to creating module distributions. @@ -216,7 +216,7 @@ treat each case individually. =item * Get a login for the Perl Authors Upload Server (PAUSE) if you don't -already have one: http://pause.perl.org +already have one: L<http://pause.perl.org> =item * @@ -248,8 +248,10 @@ Perl doesn't get more formal than that and lets you set up the package just the way that you like it (that is, it doesn't set up anything for you). -The Perl documentation has a tutorial on object oriented programming in -L<perlootut>. Also see the perl objects reference docs in L<perlobj>. +The Perl documentation has several tutorials that cover class +creation, including L<perlboot> (Barnyard Object Oriented Tutorial), +L<perltoot> (Tom's Object Oriented Tutorial), L<perlbot> (Bag o' +Object Tricks), and L<perlobj>. =head2 How can I tell if a variable is tainted? @@ -272,8 +274,8 @@ Closures are most often used in programming languages where you can have the return value of a function be itself a function, as you can in Perl. Note that some languages provide anonymous functions but are not capable of providing proper closures: the Python language, for -example. For more information on closures, check out any textbook on -functional programming. Scheme is a language that not only supports +example. For more information on closures, check out any textbook on +functional programming. Scheme is a language that not only supports but encourages closures. Here's a classic non-closure function-generating function: @@ -287,12 +289,12 @@ Here's a classic non-closure function-generating function: The anonymous subroutine returned by add_function_generator() isn't technically a closure because it refers to no lexicals outside its own -scope. Using a closure gives you a I<function template> with some +scope. Using a closure gives you a I<function template> with some customization slots left out to be filled later. Contrast this with the following make_adder() function, in which the returned anonymous function contains a reference to a lexical variable -outside the scope of that function itself. Such a reference requires +outside the scope of that function itself. Such a reference requires that Perl return a proper closure, thus locking in for all time the value that the lexical had when the function was created. @@ -305,10 +307,10 @@ value that the lexical had when the function was created. $f2 = make_adder(555); Now C<&$f1($n)> is always 20 plus whatever $n you pass in, whereas -C<&$f2($n)> is always 555 plus whatever $n you pass in. The $addpiece +C<&$f2($n)> is always 555 plus whatever $n you pass in. The $addpiece in the closure sticks around. -Closures are often used for less esoteric purposes. For example, when +Closures are often used for less esoteric purposes. For example, when you want to pass in a bit of code into a function: my $line; @@ -340,10 +342,10 @@ This problem was fixed in perl 5.004_05, so preventing it means upgrading your version of perl. ;) Variable suicide is when you (temporarily or permanently) lose the value -of a variable. It is caused by scoping through my() and local() +of a variable. It is caused by scoping through my() and local() interacting with either closures or aliased foreach() iterator variables -and subroutine arguments. It used to be easy to inadvertently lose a -variable's value this way, but now it's much harder. Take this code: +and subroutine arguments. It used to be easy to inadvertently lose a +variable's value this way, but now it's much harder. Take this code: my $f = 'foo'; sub T { @@ -374,7 +376,7 @@ The expected output is: =head2 How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}? -You need to pass references to these objects. See L<perlsub/"Pass by +You need to pass references to these objects. See L<perlsub/"Pass by Reference"> for this particular question, and L<perlref> for information on references. @@ -515,17 +517,17 @@ The discussion of closures in L<perlref> may help you even though we did not use anonymous subroutines in this answer. See L<perlsub/"Persistent Private Variables"> for details. -=head2 What's the difference between dynamic and lexical (static) scoping? Between local() and my()? +=head2 What's the difference between dynamic and lexical (static) scoping? Between local() and my()? C<local($x)> saves away the old value of the global variable C<$x> and assigns a new value for the duration of the subroutine I<which is -visible in other functions called from that subroutine>. This is done -at run-time, so is called dynamic scoping. local() always affects global +visible in other functions called from that subroutine>. This is done +at run-time, so is called dynamic scoping. local() always affects global variables, also called package variables or dynamic variables. C<my($x)> creates a new variable that is only visible in the current -subroutine. This is done at compile-time, so it is called lexical or -static scoping. my() always affects private variables, also called +subroutine. This is done at compile-time, so it is called lexical or +static scoping. my() always affects private variables, also called lexical variables or (improperly) static(ly scoped) variables. For instance: @@ -550,12 +552,12 @@ For instance: dynamic(); # prints local lexical(); # prints global -Notice how at no point does the value "private" get printed. That's +Notice how at no point does the value "private" get printed. That's because $var only has that value within the block of the lexical() function, and it is hidden from the called subroutine. In summary, local() doesn't make what you think of as private, local -variables. It gives a global variable a temporary value. my() is +variables. It gives a global variable a temporary value. my() is what you're looking for if you want private variables. See L<perlsub/"Private Variables via my()"> and @@ -596,18 +598,18 @@ dynamic variable into the current lexical scope. In deep binding, lexical variables mentioned in anonymous subroutines are the same ones that were in scope when the subroutine was created. In shallow binding, they are whichever variables with the same names -happen to be in scope when the subroutine is called. Perl always uses +happen to be in scope when the subroutine is called. Perl always uses deep binding of lexical variables (i.e., those created with my()). However, dynamic variables (aka global, local, or package variables) -are effectively shallowly bound. Consider this just one more reason -not to use them. See the answer to L<"What's a closure?">. +are effectively shallowly bound. Consider this just one more reason +not to use them. See the answer to L<"What's a closure?">. =head2 Why doesn't "my($foo) = E<lt>FILEE<gt>;" work right? C<my()> and C<local()> give list context to the right hand side -of C<=>. The <FH> read operation, like so many of Perl's +of C<=>. The <FH> read operation, like so many of Perl's functions and operators, can tell which context it was called in and -behaves appropriately. In general, the scalar() function can help. +behaves appropriately. In general, the scalar() function can help. This function does nothing to the data itself (contrary to popular myth) but rather tells its argument to behave in whatever its scalar fashion is. If that function doesn't have a defined scalar behavior, this of course @@ -632,14 +634,14 @@ Why do you want to do that? :-) If you want to override a predefined function, such as open(), then you'll have to import the new definition from a different -module. See L<perlsub/"Overriding Built-in Functions">. +module. See L<perlsub/"Overriding Built-in Functions">. If you want to overload a Perl operator, such as C<+> or C<**>, then you'll want to use the C<use overload> pragma, documented in L<overload>. If you're talking about obscuring method calls in parent classes, -see L<perlobj/"Inheritance">. +see L<perltoot/"Overridden Methods">. =head2 What's the difference between calling a function as &foo and foo()? @@ -779,7 +781,7 @@ when complex syntax is involved. =head2 How can I catch accesses to undefined variables, functions, or methods? The AUTOLOAD method, discussed in L<perlsub/"Autoloading"> and -L<perlobj/"AUTOLOAD">, lets you capture calls to +L<perltoot/"AUTOLOAD: Proxy Methods">, lets you capture calls to undefined functions and methods. When it comes to undefined variables that would trigger a warning @@ -790,18 +792,18 @@ under C<use warnings>, you can promote the warning to an error. =head2 Why can't a method included in this same file be found? Some possible reasons: your inheritance is getting confused, you've -misspelled the method name, or the object is of the wrong type. Check -out L<perlobj> for details about any of the above cases. You may +misspelled the method name, or the object is of the wrong type. Check +out L<perltoot> for details about any of the above cases. You may also use C<print ref($object)> to find out the class C<$object> was blessed into. Another possible reason for problems is that you've used the indirect object syntax (eg, C<find Guru "Samy">) on a class name -before Perl has seen that such a package exists. It's wisest to make +before Perl has seen that such a package exists. It's wisest to make sure your packages are all defined before you start using them, which will be taken care of if you use the C<use> statement instead of -C<require>. If not, make sure to use arrow notation (eg., -C<< Guru->find("Samy") >>) instead. Object notation is explained in +C<require>. If not, make sure to use arrow notation (eg., +C<< Guru->find("Samy") >>) instead. Object notation is explained in L<perlobj>. Make sure to read about creating modules in L<perlmod> and @@ -934,10 +936,10 @@ of a variable. This works I<sometimes>, but it is a very bad idea for two reasons. The first reason is that this technique I<only works on global -variables>. That means that if $fred is a lexical variable created +variables>. That means that if $fred is a lexical variable created with my() in the above example, the code wouldn't work at all: you'd accidentally access the global and skip right over the private lexical -altogether. Global variables are bad because they can easily collide +altogether. Global variables are bad because they can easily collide accidentally and in general make for non-scalable and confusing code. Symbolic references are forbidden under the C<use strict> pragma. @@ -946,9 +948,9 @@ or garbage-collected. The other reason why using a variable to hold the name of another variable is a bad idea is that the question often stems from a lack of -understanding of Perl data structures, particularly hashes. By using +understanding of Perl data structures, particularly hashes. By using symbolic references, you are just using the package's symbol-table hash -(like C<%main::>) instead of a user-defined hash. The solution is to +(like C<%main::>) instead of a user-defined hash. The solution is to use your own hash or a real reference instead. $USER_VARS{"fred"} = 23; @@ -958,8 +960,8 @@ use your own hash or a real reference instead. There we're using the %USER_VARS hash instead of symbolic references. Sometimes this comes up in reading strings from the user with variable references and wanting to expand them to the values of your perl -program's variables. This is also a bad idea because it conflates the -program-addressable namespace and the user-addressable one. Instead of +program's variables. This is also a bad idea because it conflates the +program-addressable namespace and the user-addressable one. Instead of reading a string and expanding it to the actual contents of your program's own variables: @@ -971,8 +973,8 @@ variable references actually refer to entries in that hash: $str =~ s/\$(\w+)/$USER_VARS{$1}/g; # no /e here at all -That's faster, cleaner, and safer than the previous approach. Of course, -you don't need to use a dollar sign. You could use your own scheme to +That's faster, cleaner, and safer than the previous approach. Of course, +you don't need to use a dollar sign. You could use your own scheme to make it less confusing, like bracketed percent symbols, etc. $str = 'this has a %fred% and %barney% in it'; @@ -980,7 +982,7 @@ make it less confusing, like bracketed percent symbols, etc. Another reason that folks sometimes think they want a variable to contain the name of a variable is that they don't know how to build -proper data structures using hashes. For example, let's say they +proper data structures using hashes. For example, let's say they wanted two hashes in their program: %fred and %barney, and that they wanted to use another scalar variable to refer to those by name. @@ -991,7 +993,7 @@ wanted to use another scalar variable to refer to those by name. $$name{WIFE} = "betty"; # set %barney This is still a symbolic reference, and is still saddled with the -problems enumerated above. It would be far better to write: +problems enumerated above. It would be far better to write: $folks{"fred"}{WIFE} = "wilma"; $folks{"barney"}{WIFE} = "betty"; @@ -999,13 +1001,13 @@ problems enumerated above. It would be far better to write: And just use a multilevel hash to start with. The only times that you absolutely I<must> use symbolic references are -when you really must refer to the symbol table. This may be because it's +when you really must refer to the symbol table. This may be because it's something that one can't take a real reference to, such as a format name. Doing so may also be important for method calls, since these always go through the symbol table for resolution. In those cases, you would turn off C<strict 'refs'> temporarily so you -can play around with the symbol table. For example: +can play around with the symbol table. For example: @colors = qw(red blue green yellow orange purple violet); for my $name (@colors) { @@ -1017,7 +1019,7 @@ All those functions (red(), blue(), green(), etc.) appear to be separate, but the real code in the closure actually was compiled only once. So, sometimes you might want to use symbolic references to manipulate -the symbol table directly. This doesn't matter for formats, handles, and +the symbol table directly. This doesn't matter for formats, handles, and subroutines, because they are always global--you can't use my() on them. For scalars, arrays, and hashes, though--and usually for subroutines-- you probably only want to use hard references. @@ -1026,7 +1028,7 @@ you probably only want to use hard references. (contributed by brian d foy) -The "bad interpreter" message comes from the shell, not perl. The +The "bad interpreter" message comes from the shell, not perl. The actual message may vary depending on your platform, shell, and locale settings. @@ -1061,7 +1063,7 @@ This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. Irrespective of its distribution, all code examples in this file -are hereby placed into the public domain. You are permitted and +are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun -or for profit as you see fit. A simple comment in the code giving +or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required. diff --git a/cpan/perlfaq/lib/perlfaq8.pod b/cpan/perlfaq/lib/perlfaq8.pod index 91093b134c..72447256d7 100644 --- a/cpan/perlfaq/lib/perlfaq8.pod +++ b/cpan/perlfaq/lib/perlfaq8.pod @@ -5,12 +5,12 @@ perlfaq8 - System Interaction =head1 DESCRIPTION This section of the Perl FAQ covers questions involving operating -system interaction. Topics include interprocess communication (IPC), +system interaction. Topics include interprocess communication (IPC), control over the user-interface (keyboard, screen and pointing devices), and most anything else not related to data manipulation. Read the FAQs and documentation specific to the port of perl to your -operating system (eg, L<perlvms>, L<perlplan9>, ...). These should +operating system (eg, L<perlvms>, L<perlplan9>, ...). These should contain more detailed information on the vagaries of your perl. =head2 How do I find out which operating system I'm running under? @@ -34,7 +34,7 @@ going, look at a piped C<open>, C<fork>, or C<system>. =head2 How do I do fancy stuff with the keyboard/screen/mouse? How you access/control keyboards, screens, and pointing devices -("mice") is system-dependent. Try the following modules: +("mice") is system-dependent. Try the following modules: =over 4 @@ -64,7 +64,7 @@ in this section of the perlfaq. =head2 How do I print something out in color? In general, you don't, because you don't know whether -the recipient has a color-aware display device. If you +the recipient has a color-aware display device. If you know that they have an ANSI terminal that understands color, you can use the L<Term::ANSIColor> module from CPAN: @@ -102,7 +102,7 @@ It even includes limited support for Windows. ReadMode('normal'); However, using the code requires that you have a working C compiler -and can use it to build and install a CPAN module. Here's a solution +and can use it to build and install a CPAN module. Here's a solution using the standard L<POSIX> module, which is already on your system (assuming your system supports POSIX). @@ -243,10 +243,10 @@ illustrative: =head2 How do I ask the user for a password? -(This question has nothing to do with the web. See a different +(This question has nothing to do with the web. See a different FAQ for that.) -There's an example of this in L<perlfunc/crypt>). First, you put the +There's an example of this in L<perlfunc/crypt>). First, you put the terminal into "no echo" mode, then just read the password normally. You may do this with an old-style C<ioctl()> function, POSIX terminal control (see L<POSIX> or its documentation the Camel Book), or a call @@ -262,7 +262,7 @@ from CPAN, which is easier to use and in theory more portable. =head2 How do I read and write the serial port? -This depends on which operating system your program is running on. In +This depends on which operating system your program is running on. In the case of Unix, the serial ports will be accessible through files in /dev; on other systems, device names will doubtless differ. Several problem areas common to all device interaction are the @@ -272,24 +272,24 @@ following: =item lockfiles -Your system may use lockfiles to control multiple access. Make sure -you follow the correct protocol. Unpredictable behavior can result +Your system may use lockfiles to control multiple access. Make sure +you follow the correct protocol. Unpredictable behavior can result from multiple processes reading from one device. =item open mode If you expect to use both read and write operations on the device, you'll have to open it for update (see L<perlfunc/"open"> for -details). You may wish to open it without running the risk of +details). You may wish to open it without running the risk of blocking by using C<sysopen()> and C<O_RDWR|O_NDELAY|O_NOCTTY> from the -L<Fcntl> module (part of the standard perl distribution). See +L<Fcntl> module (part of the standard perl distribution). See L<perlfunc/"sysopen"> for more on this approach. =item end of line Some devices will be expecting a "\r" at the end of each line rather -than a "\n". In some ports of perl, "\r" and "\n" are different from -their usual (Unix) ASCII values of "\015" and "\012". You may have to +than a "\n". In some ports of perl, "\r" and "\n" are different from +their usual (Unix) ASCII values of "\015" and "\012". You may have to give the numeric values you want directly, using octal ("\015"), hex ("0x0D"), or as a control-character specification ("\cM"). @@ -306,10 +306,10 @@ next. =item flushing output If you expect characters to get to your device when you C<print()> them, -you'll want to autoflush that filehandle. You can use C<select()> +you'll want to autoflush that filehandle. You can use C<select()> and the C<$|> variable to control autoflushing (see L<perlvar/$E<verbar>> and L<perlfunc/select>, or L<perlfaq5>, "How do I flush/unbuffer an -output filehandle? Why must I do this?"): +output filehandle? Why must I do this?"): $oldh = select(DEV); $| = 1; @@ -326,14 +326,14 @@ of code just because you're afraid of a little C<$|> variable: DEV->autoflush(1); As mentioned in the previous item, this still doesn't work when using -socket I/O between Unix and Macintosh. You'll need to hard code your +socket I/O between Unix and Macintosh. You'll need to hard code your line terminators, in that case. =item non-blocking input If you are doing a blocking C<read()> or C<sysread()>, you'll have to arrange for an alarm handler to provide a timeout (see -L<perlfunc/alarm>). If you have a non-blocking open, you'll likely +L<perlfunc/alarm>). If you have a non-blocking open, you'll likely have a non-blocking read, which means you may have to use a 4-arg C<select()> to determine whether I/O is ready on that device (see L<perlfunc/"select">. @@ -366,9 +366,9 @@ 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 do is check whether something else -hashes to the same string. You can't turn a hash back into the +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. @@ -404,18 +404,18 @@ this is the same thing that many of the modules will do for you). =item STDIN, STDOUT, and STDERR are shared Both the main process and the backgrounded one (the "child" process) -share the same STDIN, STDOUT and STDERR filehandles. If both try to -access them at once, strange things can happen. You may want to close -or reopen these for the child. You can get around this with +share the same STDIN, STDOUT and STDERR filehandles. If both try to +access them at once, strange things can happen. You may want to close +or reopen these for the child. You can get around this with C<open>ing a pipe (see L<perlfunc/"open">) but on some systems this means that the child process cannot outlive the parent. =item Signals You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too. -SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is +SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is sent when you write to a filehandle whose child process has closed (an -untrapped SIGPIPE can cause your program to silently die). This is +untrapped SIGPIPE can cause your program to silently die). This is not an issue with C<system("cmd&")>. =item Zombies @@ -446,14 +446,14 @@ Zombies are not an issue with C<system("prog &")>. =head2 How do I trap control characters/signals? -You don't actually "trap" a control character. Instead, that character +You don't actually "trap" a control character. Instead, that character generates a signal which is sent to your terminal's currently foregrounded process group, which you then trap in your process. Signals are documented in L<perlipc/"Signals"> and the section on "Signals" in the Camel. You can set the values of the C<%SIG> hash to be the functions you want -to handle the signal. After perl catches the signal, it looks in C<%SIG> +to handle the signal. After perl catches the signal, it looks in C<%SIG> for a key with the same name as the signal, then calls the subroutine value for that key. @@ -471,7 +471,7 @@ value for that key. Perl versions before 5.8 had in its C source code signal handlers which would catch the signal and possibly run a Perl function that you had set -in C<%SIG>. This violated the rules of signal handling at that level +in C<%SIG>. This violated the rules of signal handling at that level causing perl to dump core. Since version 5.8.0, perl looks at C<%SIG> B<after> the signal has been caught, rather than while it is being caught. Previous versions of this answer were incorrect. @@ -481,7 +481,7 @@ Previous versions of this answer were incorrect. If perl was installed correctly and your shadow library was written properly, the C<getpw*()> functions described in L<perlfunc> should in theory provide (read-only) access to entries in the shadow password -file. To change the file, make a new shadow password file (the format +file. To change the file, make a new shadow password file (the format varies from system to system--see L<passwd(1)> for specifics) and use C<pwd_mkdb(8)> to install it (see L<pwd_mkdb(8)> for more details). @@ -489,7 +489,7 @@ C<pwd_mkdb(8)> to install it (see L<pwd_mkdb(8)> for more details). Assuming you're running under sufficient permissions, you should be able to set the system-wide date and time by running the C<date(1)> -program. (There is no way to set the time and date on a per-process +program. (There is no way to set the time and date on a per-process basis.) This mechanism will work for Unix, MS-DOS, Windows, and NT; the VMS equivalent is C<set time>. @@ -505,7 +505,7 @@ X<Time::HiRes> X<BSD::Itimer> X<sleep> X<select> 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 L<Time::HiRes> and +documented in L<perlfunc/"select">. Try the L<Time::HiRes> and the L<BSD::Itimer> modules (available from CPAN, and starting from Perl 5.8 L<Time::HiRes> is part of the standard distribution). @@ -539,7 +539,7 @@ though, so if you use C<END> blocks you should also use use sigtrap qw(die normal-signals); -Perl's exception-handling mechanism is its C<eval()> operator. You +Perl's exception-handling mechanism is its C<eval()> operator. You can use C<eval()> as C<setjmp> and C<die()> as C<longjmp>. For details of this, see the section on signals, especially the time-out handler for a blocking C<flock()> in L<perlipc/"Signals"> or the @@ -551,15 +551,15 @@ many CPAN modules that handle exceptions, such as L<Try::Tiny>. If you want the C<atexit()> syntax (and an C<rmexit()> as well), try the C<AtExit> module available from CPAN. -=head2 Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean? +=head2 Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean? Some Sys-V based systems, notably Solaris 2.X, redefined some of the -standard socket constants. Since these were constant across all -architectures, they were often hardwired into perl code. The proper +standard socket constants. Since these were constant across all +architectures, they were often hardwired into perl code. The proper way to deal with this is to "use Socket" to get the correct values. Note that even though SunOS and Solaris are binary compatible, these -values are different. Go figure. +values are different. Go figure. =head2 How can I call my system's unique C functions from Perl? @@ -571,14 +571,14 @@ L<perlfunc>). Remember to check the modules that came with your distribution, and CPAN as well--someone may already have written a module to do it. On -Windows, try L<Win32::API>. On Macs, try L<Mac::Carbon>. If no module +Windows, try L<Win32::API>. On Macs, try L<Mac::Carbon>. If no module has an interface to the C function, you can inline a bit of C in your Perl source with L<Inline::C>. =head2 Where do I get the include files to do ioctl() or syscall()? Historically, these would be generated by the L<h2ph> tool, part of the -standard perl distribution. This program converts C<cpp(1)> directives +standard perl distribution. This program converts C<cpp(1)> directives in C header files to files containing subroutine definitions, like C<&SYS_getitimer>, which you can use as arguments to your functions. It doesn't work perfectly, but it usually gets most of the job done. @@ -586,32 +586,32 @@ Simple files like F<errno.h>, F<syscall.h>, and F<socket.h> were fine, but the hard ones like F<ioctl.h> nearly always need to be hand-edited. Here's how to install the *.ph files: - 1. become super-user - 2. cd /usr/include - 3. h2ph *.h */*.h + 1. become super-user + 2. cd /usr/include + 3. h2ph *.h */*.h If your system supports dynamic loading, for reasons of portability and sanity you probably ought to use L<h2xs> (also part of the standard perl -distribution). This tool converts C header files to Perl extensions. +distribution). This tool converts C header files to Perl extensions. See L<perlxstut> for how to get started with L<h2xs>. If your system doesn't support dynamic loading, you still probably -ought to use L<h2xs>. See L<perlxstut> and L<ExtUtils::MakeMaker> for +ought to use L<h2xs>. See L<perlxstut> and L<ExtUtils::MakeMaker> for more information (in brief, just use B<make perl> instead of a plain B<make> to rebuild perl with a new static extension). =head2 Why do setuid perl scripts complain about kernel problems? Some operating systems have bugs in the kernel that make setuid -scripts inherently insecure. Perl gives you a number of options +scripts inherently insecure. Perl gives you a number of options (described in L<perlsec>) to work around such systems. =head2 How can I open a pipe both to and from a command? The L<IPC::Open2> module (part of the standard perl distribution) is an easy-to-use approach that internally uses C<pipe()>, C<fork()>, and -C<exec()> to do the job. Make sure you read the deadlock warnings in -its documentation, though (see L<IPC::Open2>). See +C<exec()> to do the job. Make sure you read the deadlock warnings in +its documentation, though (see L<IPC::Open2>). See L<perlipc/"Bidirectional Communication with Another Process"> and L<perlipc/"Bidirectional Communication with Yourself"> @@ -621,10 +621,10 @@ arguments from L<IPC::Open2> (see L<IPC::Open3>). =head2 Why can't I get the output of a command with system()? -You're confusing the purpose of C<system()> and backticks (``). C<system()> +You're confusing the purpose of C<system()> and backticks (``). C<system()> runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and -the high 8 bits are the actual exit value). Backticks (``) run a +the high 8 bits are the actual exit value). Backticks (``) run a command and return what it sent to STDOUT. $exit_status = system("mail-users"); @@ -642,7 +642,7 @@ With C<system()>, both STDOUT and STDERR will go the same place as the script's STDOUT and STDERR, unless the C<system()> command redirects them. Backticks and C<open()> read B<only> the STDOUT of your command. -You can also use the C<open3()> function from L<IPC::Open3>. Benjamin +You can also use the C<open3()> function from L<IPC::Open3>. Benjamin Goldberg provides some sample code: To capture a program's STDOUT, but discard its STDERR: @@ -728,7 +728,7 @@ This doesn't work: $alloutput = `cmd args`; # stderr still escapes This fails because the C<open()> makes STDERR go to where STDOUT was -going at the time of the C<open()>. The backticks then make STDOUT go to +going at the time of the C<open()>. The backticks then make STDOUT go to a string, but don't change STDERR (which still goes to the old STDOUT). @@ -736,7 +736,7 @@ Note that you I<must> use Bourne shell (C<sh(1)>) redirection syntax in backticks, not C<csh(1)>! Details on why Perl's C<system()> and backtick and pipe opens all use the Bourne shell are in the F<versus/csh.whynot> article in the "Far More Than You Ever Wanted To -Know" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz . To +Know" collection in L<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> . To capture a command's STDERR and STDOUT together: $output = `cmd 2>&1`; # either with backticks @@ -768,25 +768,25 @@ when the program is done: system("program args 1>program.stdout 2>program.stderr"); -Ordering is important in all these examples. That's because the shell +Ordering is important in all these examples. That's because the shell processes file descriptor redirections in strictly left to right order. system("prog args 1>tmpfile 2>&1"); system("prog args 2>&1 1>tmpfile"); The first command sends both standard out and standard error to the -temporary file. The second command sends only the old standard output +temporary file. The second command sends only the old standard output there, and the old standard error shows up on the old standard out. =head2 Why doesn't open() return an error when a pipe open fails? If the second argument to a piped C<open()> contains shell metacharacters, perl C<fork()>s, then C<exec()>s a shell to decode the -metacharacters and eventually run the desired program. If the program +metacharacters and eventually run the desired program. If the program couldn't be run, it's the shell that gets the message, not Perl. All your Perl program can find out is whether the shell itself could be -successfully started. You can still capture the shell's STDERR and -check it for error messages. See L<"How can I capture STDERR from an +successfully started. You can still capture the shell's STDERR and +check it for error messages. See L<"How can I capture STDERR from an external command?"> elsewhere in this document, or use the L<IPC::Open3> module. @@ -796,10 +796,10 @@ report whether the command started. =head2 What's wrong with using backticks in a void context? -Strictly speaking, nothing. Stylistically speaking, it's not a good -way to write maintainable code. Perl has several operators for -running external commands. Backticks are one; they collect the output -from the command for use in your program. The C<system> function is +Strictly speaking, nothing. Stylistically speaking, it's not a good +way to write maintainable code. Perl has several operators for +running external commands. Backticks are one; they collect the output +from the command for use in your program. The C<system> function is another; it doesn't do this. Writing backticks in your program sends a clear message to the readers @@ -811,7 +811,7 @@ Consider this line: `cat /etc/termcap`; You forgot to check C<$?> to see whether the program even ran -correctly. Even if you wrote +correctly. Even if you wrote print `cat /etc/termcap`; @@ -829,7 +829,7 @@ processing may take place, whereas backticks do not. =head2 How can I call backticks without shell processing? -This is a bit tricky. You can't simply write the command +This is a bit tricky. You can't simply write the command like this: @ok = `grep @opts '$search_string' @filenames`; @@ -860,7 +860,7 @@ list. Further examples of this can be found in L<perlipc/"Safe Pipe Opens">. Note that if you're using Windows, no solution to this vexing issue is -even possible. Even though Perl emulates C<fork()>, you'll still be +even possible. Even though Perl emulates C<fork()>, you'll 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)? @@ -868,8 +868,8 @@ stuck, because Windows does not have an argc/argv-style API. This happens only if your perl is compiled to use stdio instead of perlio, which is the default. Some (maybe all?) stdios set error and eof flags that you may need to clear. The L<POSIX> module defines -C<clearerr()> that you can use. That is the technically correct way to -do it. Here are some less reliable workarounds: +C<clearerr()> that you can use. That is the technically correct way to +do it. Here are some less reliable workarounds: =over 4 @@ -898,10 +898,10 @@ If that doesn't work, give up on your stdio package and use sysread. =head2 How can I convert my shell script to perl? -Learn Perl and rewrite it. Seriously, there's no simple converter. +Learn Perl and rewrite it. Seriously, there's no simple converter. Things that are awkward to do in the shell are easy to do in Perl, and this very awkwardness is what would make a shell->perl converter -nigh-on impossible to write. By rewriting it, you'll think about what +nigh-on impossible to write. By rewriting it, you'll think about what you're really trying to do, and hopefully will escape the shell's pipeline datastream paradigm, which while convenient for some matters, causes many inefficiencies. @@ -910,7 +910,7 @@ causes many inefficiencies. Try the L<Net::FTP>, L<TCP::Client>, and L<Net::Telnet> modules (available from CPAN). -http://www.cpan.org/scripts/netstuff/telnet.emul.shar will also help +L<http://www.cpan.org/scripts/netstuff/telnet.emul.shar> will also help for emulating the telnet protocol, but L<Net::Telnet> is quite probably easier to use. @@ -919,8 +919,8 @@ the initial telnet handshaking, then the standard dual-process approach will suffice: use IO::Socket; # new in 5.004 - $handle = IO::Socket::INET->new('www.perl.com:80') - or die "can't connect to port 80 on www.perl.com: $!"; + $handle = IO::Socket::INET->new('L<www.perl.com:80')> + or die "can't connect to port 80 on L<www.perl.com:> $!"; $handle->autoflush(1); if (fork()) { # XXX: undef means failure select($handle); @@ -934,8 +934,8 @@ approach will suffice: =head2 How can I write expect in Perl? Once upon a time, there was a library called F<chat2.pl> (part of the -standard perl distribution), which never really got finished. If you -find it somewhere, I<don't use it>. These days, your best bet is to +standard perl distribution), which never really got finished. If you +find it somewhere, I<don't use it>. These days, your best bet is to look at the Expect module available from CPAN, which also requires two other modules from CPAN, L<IO::Pty> and L<IO::Stty>. @@ -944,26 +944,26 @@ other modules from CPAN, L<IO::Pty> and L<IO::Stty>. First of all note that if you're doing this for security reasons (to avoid people seeing passwords, for example) then you should rewrite your program so that critical information is never given as an -argument. Hiding the arguments won't make your program completely +argument. Hiding the arguments won't make your program completely secure. To actually alter the visible command line, you can assign to the -variable $0 as documented in L<perlvar>. This won't work on all -operating systems, though. Daemon programs like sendmail place their +variable $0 as documented in L<perlvar>. This won't work on all +operating systems, though. Daemon programs like sendmail place their state there, as in: $0 = "orcus [accepting connections]"; -=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? +=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? =over 4 =item Unix In the strictest sense, it can't be done--the script executes as a -different process from the shell it was started from. Changes to a +different process from the shell it was started from. Changes to a process are not reflected in its parent--only in any children -created after the change. There is shell magic that may allow you to +created after the change. There is shell magic that may allow you to fake it by C<eval()>ing the script's output in your shell; check out the comp.unix.questions FAQ for details. @@ -972,22 +972,22 @@ comp.unix.questions FAQ for details. =head2 How do I close a process's filehandle without waiting for it to complete? Assuming your system supports such things, just send an appropriate signal -to the process (see L<perlfunc/"kill">). It's common to first send a TERM +to the process (see L<perlfunc/"kill">). It's common to first send a TERM signal, wait a little bit, and then send a KILL signal to finish it off. =head2 How do I fork a daemon process? If by daemon process you mean one that's detached (disassociated from its tty), then the following process is reported to work on most -Unixish systems. Non-Unix users should check their Your_OS::Process +Unixish systems. Non-Unix users should check their Your_OS::Process module for other solutions. =over 4 =item * -Open /dev/tty and use the TIOCNOTTY ioctl on it. See L<tty(1)> -for details. Or better yet, you can just use the C<POSIX::setsid()> +Open /dev/tty and use the TIOCNOTTY ioctl on it. See L<tty(1)> +for details. Or better yet, you can just use the C<POSIX::setsid()> function, so you don't have to worry about process groups. =item * @@ -1055,7 +1055,7 @@ Testers, for instance, set the value of C<AUTOMATED_TESTING>: Use the C<alarm()> function, probably in conjunction with a signal handler, as documented in L<perlipc/"Signals"> and the section on -"Signals" in the Camel. You may instead use the more flexible +"Signals" in the Camel. You may instead use the more flexible L<Sys::AlarmCall> module available from CPAN. The C<alarm()> function is not implemented on all versions of Windows. @@ -1074,7 +1074,7 @@ Use the L<BSD::Resource> module from CPAN. As an example: 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, 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. @@ -1091,19 +1091,19 @@ in L<perlfaq8/"How do I start a process in the background?">. The L<DBI> module provides an abstract interface to most database servers and types, including Oracle, DB2, Sybase, mysql, Postgresql, -ODBC, and flat files. The DBI module accesses each database type -through a database driver, or DBD. You can see a complete list of -available drivers on CPAN: http://www.cpan.org/modules/by-module/DBD/ . -You can read more about DBI on http://dbi.perl.org . +ODBC, and flat files. The DBI module accesses each database type +through a database driver, or DBD. You can see a complete list of +available drivers on CPAN: L<http://www.cpan.org/modules/by-module/DBD/> . +You can read more about DBI on L<http://dbi.perl.org> . Other modules provide more specific access: L<Win32::ODBC>, L<Alzabo>, -C<iodbc>, and others found on CPAN Search: http://search.cpan.org . +C<iodbc>, and others found on CPAN Search: L<http://search.cpan.org> . =head2 How do I make a system() exit on control-C? -You can't. You need to imitate the C<system()> call (see L<perlipc> for +You can't. You need to imitate the C<system()> call (see L<perlipc> for sample code) and then have a signal handler for the INT signal that -passes the signal on to the subprocess. Or you can check for it: +passes the signal on to the subprocess. Or you can check for it: $rc = system($cmd); if ($rc & 127) { die "signal death" } @@ -1124,8 +1124,8 @@ C<sysopen()>: (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 -emit its own warnings and error messages. Most of the time you cannot +and that something else may output error messages. The script might +emit its own warnings and error messages. Most of the time you cannot tell who said what. You probably cannot fix the thing that runs perl, but you can change how @@ -1138,7 +1138,7 @@ Consider this script, which has an error you may not notice immediately. print "Hello World\n"; I get an error when I run this from my shell (which happens to be -bash). That may look like perl forgot it has a C<print()> function, +bash). That may look like perl forgot it has a C<print()> function, but my shebang line is not the path to perl, so the shell runs the script, and I get the error. @@ -1159,7 +1159,7 @@ you need to figure out the problem. $x / 0; __END__ -The perl message comes out with "Perl" in front. The C<BEGIN> block +The perl message comes out with "Perl" in front. The C<BEGIN> block works at compile time so all of the compilation errors and warnings get the "Perl:" prefix too. @@ -1174,12 +1174,12 @@ get the "Perl:" prefix too. If I don't see that "Perl:", it's not from perl. You could also just know all the perl errors, and although there are -some people who may know all of them, you probably don't. However, they +some people who may know all of them, you probably don't. However, they all should be in the L<perldiag> manpage. If you don't find the error in there, it probably isn't a perl error. Looking up every message is not the easiest way, so let perl to do it -for you. Use the diagnostics pragma with turns perl's normal messages +for you. Use the diagnostics pragma with turns perl's normal messages into longer discussions on the topic. use diagnostics; @@ -1297,7 +1297,7 @@ You can configure C<CPAN.pm> to automatically use this option too: cpan> o conf commit 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 +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 modules. @@ -1392,14 +1392,14 @@ environment variables, run-time switches, and in-code statements: =back The last is particularly useful because it knows about machine-dependent -architectures. The C<lib.pm> pragmatic module was first +architectures. The C<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 Perl 4 style file defining values for system networking -constants. Sometimes it is built using L<h2ph> when Perl is installed, -but other times it is not. Modern programs C<use Socket;> instead. +constants. Sometimes it is built using L<h2ph> when Perl is installed, +but other times it is not. Modern programs C<use Socket;> instead. =head1 AUTHOR AND COPYRIGHT @@ -1410,7 +1410,7 @@ This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. Irrespective of its distribution, all code examples in this file -are hereby placed into the public domain. You are permitted and +are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun -or for profit as you see fit. A simple comment in the code giving +or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required. diff --git a/cpan/perlfaq/lib/perlfaq9.pod b/cpan/perlfaq/lib/perlfaq9.pod index 81e7613fc8..63bb80e67d 100644 --- a/cpan/perlfaq/lib/perlfaq9.pod +++ b/cpan/perlfaq/lib/perlfaq9.pod @@ -14,10 +14,10 @@ and a few on the web. The Common Gateway Interface (CGI) specifies a software interface between a program ("CGI script") and a web server (HTTPD). It is not specific to Perl, and has its own FAQs and tutorials, and usenet group, -comp.infosystems.www.authoring.cgi +comp.infosystems.L<www.authoring.cgi> The CGI specification is outlined in an informational RFC: -http://www.ietf.org/rfc/rfc3875 +L<http://www.ietf.org/rfc/rfc3875> These Perl FAQs very selectively cover some CGI issues. However, Perl programmers are strongly advised to use the C<CGI.pm> module, to take care @@ -49,14 +49,14 @@ systems. C<CGI.pm> selects an appropriate newline representation There are many things that might be wrong with your CGI program, and only some of them might be related to Perl. Try going through the L<troubleshooting -guide|http://www.perlmonks.org/?node_id=380424> on -L<Perlmonks|http://www.perlmonks.org> +guide|L<http://www.perlmonks.org/?node_id=380424>> on +L<Perlmonks|L<http://www.perlmonks.org>> =head2 How can I get better error messages from a CGI program? -Use the L<CGI::Carp> module. It replaces C<warn> and C<die>, plus the +Use the L<CGI::Carp> module. It replaces C<warn> and C<die>, plus the normal L<Carp> module's C<carp>, C<croak>, and C<confess> functions with -more verbose and safer versions. It still sends them to the normal +more verbose and safer versions. It still sends them to the normal server error log. use CGI::Carp; @@ -88,14 +88,14 @@ stamp prepended. =head2 How do I remove HTML from a string? The most correct way (albeit not the fastest) is to use L<HTML::Parser> -from CPAN. Another mostly correct +from CPAN. Another mostly correct way is to use L<HTML::FormatText> which not only removes HTML but also attempts to do a little simple formatting of the resulting plain text. Many folks attempt a simple-minded regular expression approach, like C<< s/<.*?>//g >>, but that fails in many cases because the tags may continue over line breaks, they may contain quoted angle-brackets, -or HTML comments may be present. Plus, folks forget to convert +or HTML comments may be present. Plus, folks forget to convert entities--like C<<> for example. Here's one "simple-minded" approach, that works for most files: @@ -105,7 +105,7 @@ Here's one "simple-minded" approach, that works for most files: If you want a more complete solution, see the 3-stage striphtml program in -http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz +L<http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz> . Here are some tricky cases that you should think about when picking @@ -135,16 +135,16 @@ on text like this: You can easily extract all sorts of URLs from HTML with L<HTML::SimpleLinkExtor> which handles anchors, images, objects, -frames, and many other tags that can contain a URL. If you need +frames, and many other tags that can contain a URL. If you need anything more complex, you can create your own subclass of -L<HTML::LinkExtor> or L<HTML::Parser>. You might even use +L<HTML::LinkExtor> or L<HTML::Parser>. You might even use L<HTML::SimpleLinkExtor> as an example for something specifically suited to your needs. You can use L<URI::Find> to extract URLs from an arbitrary text document. Less complete solutions involving regular expressions can save -you a lot of processing time if you know that the input is simple. One +you a lot of processing time if you know that the input is simple. One solution from Tom Christiansen runs 100 times faster than most module-based approaches but only extracts URLs from anchors where the first attribute is HREF and there are no other attributes. @@ -157,13 +157,13 @@ attribute is HREF and there are no other attributes. \s* > }gsix; -=head2 How do I download a file from the user's machine? How do I open a file on another machine? +=head2 How do I download a file from the user's machine? How do I open a file on another machine? In this case, download means to use the file upload feature of HTML -forms. You allow the web surfer to specify a file to send to your web -server. To you it looks like a download, and to the user it looks -like an upload. No matter what you call it, you do it with what's -known as B<multipart/form-data> encoding. The C<CGI.pm> module (which +forms. You allow the web surfer to specify a file to send to your web +server. To you it looks like a download, and to the user it looks +like an upload. No matter what you call it, you do it with what's +known as B<multipart/form-data> encoding. The C<CGI.pm> module (which comes with Perl as part of the Standard Library) supports this in the C<start_multipart_form()> method, which isn't the same as the C<startform()> method. @@ -203,13 +203,13 @@ resources and give their content back to you as a string: use LWP::Simple qw(get); - my $html = get( "http://www.example.com/index.html" ); + my $html = get( "L<http://www.example.com/index.html"> ); It can also store the resource directly in a file: use LWP::Simple qw(getstore); - getstore( "http://www.example.com/index.html", "foo.html" ); + getstore( "L<http://www.example.com/index.html">, "foo.html" ); If you need to do something more complicated, you can use L<LWP::UserAgent> module to create your own user-agent (e.g. browser) @@ -219,7 +219,7 @@ browser, you can use the L<WWW::Mechanize> module. =head2 How do I automate an HTML form submission? If you are doing something complex, such as moving through many pages -and forms or a web site, you can use L<WWW::Mechanize>. See its +and forms or a web site, you can use L<WWW::Mechanize>. See its documentation for all the details. If you're submitting values using the GET method, create a URL and encode @@ -228,7 +228,7 @@ the form using the C<query_form> method: use LWP::Simple; use URI::URL; - my $url = url('http://www.perl.com/cgi-bin/cpan_mod'); + my $url = url('L<http://www.perl.com/cgi-bin/cpan_mod')>; $url->query_form(module => 'DB_File', readme => 1); $content = get($url); @@ -239,7 +239,7 @@ the content appropriately. use LWP::UserAgent; $ua = LWP::UserAgent->new(); - my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod', + my $req = POST 'L<http://www.perl.com/cgi-bin/cpan_mod'>, [ module => 'DB_File', readme => 1 ]; $content = $ua->request($req)->as_string; @@ -294,15 +294,15 @@ script. The other kind (an absolute URLpath) is resolved internally to the server without any HTTP redirection. The CGI specifications do not allow relative URLs in either case. -Use of C<CGI.pm> is strongly recommended. This example shows redirection +Use of C<CGI.pm> is strongly recommended. This example shows redirection with a complete URL. This redirection is handled by the web browser. use CGI qw/:standard/; - my $url = 'http://www.cpan.org/'; + my $url = 'L<http://www.cpan.org/'>; print redirect($url); -This example shows a redirection with an absolute URLpath. This +This example shows a redirection with an absolute URLpath. This redirection is handled by the local web server. my $url = '/CPAN/index.html'; @@ -318,18 +318,18 @@ an absolute URLpath. =head2 How do I put a password on my web pages? To enable authentication for your web server, you need to configure -your web server. The configuration is different for different sorts +your web server. The configuration is different for different sorts of web servers--apache does it differently from iPlanet which does -it differently from IIS. Check your web server documentation for +it differently from IIS. Check your web server documentation for the details for your particular server. =head2 How do I edit my .htpasswd and .htgroup files with Perl? The L<HTTPD::UserAdmin> and L<HTTPD::GroupAdmin> modules provide a consistent OO interface to these files, regardless of how they're -stored. Databases may be text, dbm, Berkeley DB or any database with -a DBI compatible driver. L<HTTPD::UserAdmin> supports files used by the -"Basic" and "Digest" authentication schemes. Here's an example: +stored. Databases may be text, dbm, Berkeley DB or any database with +a DBI compatible driver. L<HTTPD::UserAdmin> supports files used by the +"Basic" and "Digest" authentication schemes. Here's an example: use HTTPD::UserAdmin (); HTTPD::UserAdmin @@ -356,25 +356,31 @@ using any data that you don't intend to use. Trust no one. =head2 How do I parse a mail header? -For a quick-and-dirty solution, try this solution derived -from L<perlfunc/split>: +Use the L<Email::MIME> module. It's well-tested and supports all the +craziness that you'll see in the real world (comment-folding whitespace, +encodings, comments, etc.). - $/ = ''; - $header = <MSG>; - $header =~ s/\n\s+/ /g; # merge continuation lines - %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header ); + use Email::MIME; -That solution doesn't do well if, for example, you're trying to -maintain all the Received lines. A more complete approach is to use -the L<Mail::Header> module from CPAN (part of the L<MailTools> package). + my $message = Email::MIME->new($rfc2822); + my $subject = $message->header('Subject'); + my $from = $message->header('From'); + +If you've already got some other kind of email object, consider passing +it to L<Email::Abstract> and then using its cast method to get an +L<Email::MIME> object: + + my $mail_message_object = read_message(); + my $abstract = Email::Abstract->new($mail_message_object); + my $email_mime_object = $abstract->cast('Email::MIME'); =head2 How do I decode a CGI form? (contributed by brian d foy) -Use the C<CGI.pm> module that comes with Perl. It's quick, +Use the C<CGI.pm> module that comes with Perl. It's quick, it's easy, and it actually does quite a bit of work to -ensure things happen correctly. It handles GET, POST, and +ensure things happen correctly. It handles GET, POST, and HEAD requests, multipart forms, multivalued fields, query string and message body combinations, and many other things you probably don't want to think about. @@ -400,18 +406,18 @@ If you want an object-oriented approach, C<CGI.pm> can do that too. my @items = $cgi->param( 'item' ); You might also try L<CGI::Minimal> which is a lightweight version -of the same thing. Other CGI::* modules on CPAN might work better +of the same thing. Other CGI::* modules on CPAN might work better for you, too. Many people try to write their own decoder (or copy one from another program) and then run into one of the many "gotchas" -of the task. It's much easier and less hassle to use C<CGI.pm>. +of the task. It's much easier and less hassle to use C<CGI.pm>. =head2 How do I check a valid mail address? (partly contributed by Aaron Sherman) -This isn't as simple a question as it sounds. There are two parts: +This isn't as simple a question as it sounds. There are two parts: a) How do I verify that an email address is correctly formatted? @@ -419,32 +425,8 @@ b) How do I verify that an email address targets a valid recipient? Without sending mail to the address and seeing whether there's a human on the other end to answer you, you cannot fully answer part I<b>, but -either the L<Email::Valid> or the C<RFC::RFC822::Address> module will do -both part I<a> and part I<b> as far as you can in real-time. - -If you want to just check part I<a> to see that the address is valid -according to the mail header standard with a simple regular expression, -you can have problems, because there are deliverable addresses that -aren't RFC-2822 (the latest mail header standard) compliant, and -addresses that aren't deliverable which, are compliant. However, the -following will match valid RFC-2822 addresses that do not have comments, -folding whitespace, or any other obsolete or non-essential elements. -This I<just> matches the address itself: - - my $atom = qr{[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+}; - my $dot_atom = qr{$atom(?:\.$atom)*}; - my $quoted = qr{"(?:\\[^\r\n]|[^\\"])*"}; - my $local = qr{(?:$dot_atom|$quoted)}; - my $quotedpair = qr{\\[\x00-\x09\x0B-\x0c\x0e-\x7e]}; - my $domain_lit = qr{\[(?:$quotedpair|[\x21-\x5a\x5e-\x7e])*\]}; - my $domain = qr{(?:$dot_atom|$domain_lit)}; - my $addr_spec = qr{$local\@$domain}; - -Just match an address against C</^${addr_spec}$/> to see if it follows -the RFC2822 specification. However, because it is impossible to be -sure that such a correctly formed address is actually the correct way -to reach a particular person or even has a mailbox associated with it, -you must be very careful about how you use this. +the L<Email::Valid> module will do both part I<a> and part I<b> as far +as you can in real-time. Our best advice for verifying a person's mail address is to have them enter their address twice, just as you normally do to change a @@ -454,165 +436,115 @@ back and they've followed your directions, you can be reasonably assured that it's real. A related strategy that's less open to forgery is to give them a PIN -(personal ID number). Record the address and PIN (best that it be a -random one) for later processing. In the mail you send, ask them to -include the PIN in their reply. But if it bounces, or the message is -included via a "vacation" script, it'll be there anyway. So it's -best to ask them to mail back a slight alteration of the PIN, such as -with the characters reversed, one added or subtracted to each digit, etc. +(personal ID number). Record the address and PIN (best that it be a +random one) for later processing. In the mail you send, include a link to +your site with the PIN included. If the mail bounces, you know it's not +valid. If they don't click on the link, either they forged the address or +(assuming they got the message) following through wasn't important so you +don't need to worry about it. =head2 How do I decode a MIME/BASE64 string? -The L<MIME::Base64> package (available from CPAN) handles this as well as -the MIME/QP encoding. Decoding BASE64 becomes as simple as: +The L<MIME::Base64> package handles this as well as the MIME/QP encoding. +Decoding base 64 becomes as simple as: use MIME::Base64; $decoded = decode_base64($encoded); -The L<MIME::Tools> package (available from CPAN) supports extraction with -decoding of BASE64 encoded attachments and content directly from email -messages. +The L<Email::MIME> module can decode base 64-encoded email message parts +transparently so the developer doesn't need to worry about it. -If the string to decode is short (less than 84 bytes long) -a more direct approach is to use the C<unpack()> function's "u" -format after minor transliterations: +=head2 How do I return the user's mail address? - tr#A-Za-z0-9+/##cd; # remove non-base64 chars - tr#A-Za-z0-9+/# -_#; # convert to uuencoded format - $len = pack("c", 32 + 0.75*length); # compute length byte - print unpack("u", $len . $_); # uudecode and print +Ask them for it. There are so many email providers available that it's +rather unlikely the local system has any idea how to determine a user's +email address. The one notable exception is for organization-specific +email (e.g. foo@yourcompany.com) where policy can be codified in your +program. In that case, you can look at $ENV{USER}, $ENV{LOGNAME}, and +getpwuid($<) in scalar context, like so: -=head2 How do I return the user's mail address? + my $user_name = getpwuid($<) -On systems that support getpwuid, the C<< $< >> variable, and the -L<Sys::Hostname> module (which is part of the standard perl distribution), -you can probably try using something like this: +But note that you still cannot make any assumptions about whether this +is correct unless your policy says it is. And then there are things like +localpart extensions (foo+bar@example.com). You really are best off +asking the user. - use Sys::Hostname; - $address = sprintf('%s@%s', scalar getpwuid($<), hostname); +=head2 How do I send mail? -Company policies on mail address can mean that this generates addresses -that the company's mail system will not accept, so you should ask for -users' mail addresses when this matters. Furthermore, not all systems -on which Perl runs are so forthcoming with this information as is Unix. +Use the L<Email::MIME> and L<Email::Sender::Simple> modules, like so: -The L<Mail::Util> module from CPAN (part of the L<MailTools> package) provides a -C<mailaddress()> function that tries to guess the mail address of the user. -It makes a more intelligent guess than the code above, using information -given when the module was installed, but it could still be incorrect. -Again, the best way is often just to ask the user. + # first, create your message + my $message = Email::MIME->create( + header_str => [ + From => 'you@example.com', + To => 'friend@example.com', + Subject => 'Happy birthday!', + ], + body_str => 'Happy birthday to you!', + ); -=head2 How do I send mail? + use Email::Sender::Simple qw(sendmail); + sendmail($message); -Use the C<sendmail> program directly: - - open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq") - or die "Can't fork for sendmail: $!\n"; - print SENDMAIL <<"EOF"; - From: User Originating Mail <me\@host> - To: Final Destination <you\@otherhost> - Subject: A relevant subject line - - Body of the message goes here after the blank line - in as many lines as you like. - EOF - close(SENDMAIL) or warn "sendmail didn't close nicely"; - -The B<-oi> option prevents C<sendmail> from interpreting a line consisting -of a single dot as "end of message". The B<-t> option says to use the -headers to decide who to send the message to, and B<-odq> says to put -the message into the queue. This last option means your message won't -be immediately delivered, so leave it out if you want immediate -delivery. - -Alternate, less convenient approaches include calling C<mail> (sometimes -called C<mailx>) directly or simply opening up port 25 have having an -intimate conversation between just you and the remote SMTP daemon, -probably C<sendmail>. - -Or you might be able use the CPAN module L<Mail::Mailer>: - - use Mail::Mailer; - - $mailer = Mail::Mailer->new(); - $mailer->open({ From => $from_address, - To => $to_address, - Subject => $subject, - }) - or die "Can't open: $!\n"; - print $mailer $body; - $mailer->close(); - -The L<Mail::Internet> module uses L<Net::SMTP> which is less Unix-centric than -L<Mail::Mailer>, but less reliable. Avoid raw SMTP commands. There -are many reasons to use a mail transport agent like C<sendmail>. These -include queuing, MX records, and security. +By default, L<Email::Sender::Simple> will try `sendmail` first, if it exists +in your $PATH. This generally isn't the case. If there's a remote mail +server you use to send mail, consider investigating one of the Transport +classes. At time of writing, the available transports include: -=head2 How do I use MIME to make an attachment to a mail message? +=over 4 -This answer is extracted directly from the L<MIME::Lite> documentation. -Create a multipart message (i.e., one with attachments). +=item L<Email::Sender::Transport::Sendmail> - use MIME::Lite; +This is the default. If you can use the L<mail(1)> or L<mailx(1)> +program to send mail from the machine where your code runs, you should +be able to use this. - ### Create a new multipart message: - $msg = MIME::Lite->new( - From =>'me@myhost.com', - To =>'you@yourhost.com', - Cc =>'some@other.com, some@more.com', - Subject =>'A message with 2 parts...', - Type =>'multipart/mixed' - ); +=item L<Email::Sender::Transport::SMTP> - ### Add parts (each "attach" has same arguments as "new"): - $msg->attach(Type =>'TEXT', - Data =>"Here's the GIF file you wanted" - ); - $msg->attach(Type =>'image/gif', - Path =>'aaa000123.gif', - Filename =>'logo.gif' - ); +This transport contacts a remote SMTP server over TCP. It optionally +uses SSL and can authenticate to the server via SASL. - $text = $msg->as_string; +=item L<Email::Sender::Transport::SMTP::TLS> -L<MIME::Lite> also includes a method for sending these things. +This is like the SMTP transport, but uses TLS security. You can +authenticate with this module as well, using any mechanisms your server +supports after STARTTLS. - $msg->send; +=back -This defaults to using L<sendmail(1)> but can be customized to use -SMTP via L<Net::SMTP>. +Telling L<Email::Sender::Simple> to use your transport is straightforward. + + sendmail( + $message, + { + transport => $email_sender_transport_object, + } + ); + +=head2 How do I use MIME to make an attachment to a mail message? + +L<Email::MIME> directly supports multipart messages. L<Email::MIME> +objects themselves are parts and can be attached to other L<Email::MIME> +objects. Consult the L<Email::MIME> documentation for more information, +including all of the supported methods and examples of their use. =head2 How do I read mail? -While you could use the L<Mail::Folder> module from CPAN (part of the -L<MailFolder> package) or the L<Mail::Internet> module from CPAN (part -of the L<MailTools> package), often a module is overkill. Here's a -mail sorter. - - #!/usr/bin/perl - - my(@msgs, @sub); - my $msgno = -1; - $/ = ''; # paragraph reads - while (<>) { - if (/^From /m) { - /^Subject:\s*(?:Re:\s*)*(.*)/mi; - $sub[++$msgno] = lc($1) || ''; - } - $msgs[$msgno] .= $_; - } - for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) { - print $msgs[$i]; - } +Use the L<Email::Folder> module, like so: -Or more succinctly, + use Email::Folder; - #!/usr/bin/perl -n00 - # bysub2 - awkish sort-by-subject - BEGIN { $msgno = -1 } - $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m; - $msg[$msgno] .= $_; - END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] } + my $folder = Email::Folder->new('/path/to/email/folder'); + while(my $message = $folder->next_message) { + # next_message returns Email::Simple objects, but we want + # Email::MIME objects as they're more robust + my $mime = Email::MIME->new($message->as_string); + } + +There are different classes in the L<Email::Folder> namespace for +supporting various mailbox types. Note that these modules are generally +rather limited and only support B<reading> rather than writing. =head2 How do I find out my hostname, domainname, or IP address? X<hostname, domainname, IP address, host, domain, hostfqdn, inet_ntoa, @@ -635,6 +567,14 @@ hostname: $host = hostname(); + +The L<Sys::Hostname::Long> module takes a different approach and tries +harder to return the fully qualified hostname: + + use Sys::Hostname::Long 'hostname_long'; + + my $hostname = hostname_long(); + To get the IP address, you can use the C<gethostbyname> built-in function to turn the name into a number. To turn that number into the dotted octet form (a.b.c.d) that most people expect, use the C<inet_ntoa> function @@ -644,7 +584,7 @@ from the L<Socket> module, which also comes with perl. my $address = inet_ntoa( scalar gethostbyname( $host || 'localhost' ) - ); + ); =head2 How do I fetch a news article or the active newsgroups? @@ -664,7 +604,7 @@ makes it quite easy to fetch a file: use LWP::Simple; - my $data = get( 'ftp://some.ftp.site/some/file.txt' ); + my $data = get( 'L<ftp://some.ftp.site/some/file.txt'> ); If you want more direct or low-level control of the FTP process, you can use the L<Net::FTP> module (in the Standard Library since Perl 5.8). It's @@ -675,7 +615,7 @@ documentation has examples showing you just how to do that. (contributed by brian d foy) Use one of the RPC modules you can find on CPAN ( -http://search.cpan.org/search?query=RPC&mode=all ). +L<http://search.cpan.org/search?query=RPC&mode=all> ). =head1 AUTHOR AND COPYRIGHT @@ -686,7 +626,7 @@ This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. Irrespective of its distribution, all code examples in this file -are hereby placed into the public domain. You are permitted and +are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun -or for profit as you see fit. A simple comment in the code giving +or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required. |