{
    "mode": "perldoc",
    "parameter": "L",
    "section": "-q",
    "url": "https://www.chedong.com/phpMan.php/perldoc/L/json",
    "generated": "2026-10-10T16:53:56Z",
    "sections": {
        "Found in /usr/share/perl/5.38/pod/perlfaq1.pod": {
            "content": "What is Perl?\nPerl is a high-level programming language with an eclectic heritage\nwritten by Larry Wall and a cast of thousands.\n\nPerl's process, file, and text manipulation facilities make it\nparticularly well-suited for tasks involving quick prototyping, system\nutilities, software tools, system management tasks, database access,\ngraphical programming, networking, and web programming.\n\nPerl derives from the ubiquitous C programming language and to a lesser\nextent from sed, awk, the Unix shell, and many other tools and\nlanguages.\n\nThese strengths make it especially popular with web developers and\nsystem administrators. Mathematicians, geneticists, journalists,\nmanagers and many other people also use Perl.\n\nWho supports Perl? Who develops it? Why is it free?\nThe original culture of the pre-populist Internet and the deeply-held\nbeliefs of Perl's author, Larry Wall, gave rise to the free and open\ndistribution policy of Perl. Perl is supported by its users. The core,\nthe standard Perl library, the optional modules, and the documentation\nyou're reading now were all written by volunteers.\n\nThe core development team (known as the Perl Porters) are a group of\nhighly altruistic individuals committed to producing better software for\nfree than you could hope to purchase for money. You may snoop on pending\ndevelopments via the archives\n<http://www.nntp.perl.org/group/perl.perl5.porters/> or you can\nsubscribe to the mailing list by sending\nperl5-porters-subscribe@perl.org a subscription request (an empty\nmessage with no subject is fine).\n\nWhile the GNU project includes Perl in its distributions, there's no\nsuch thing as \"GNU Perl\". Perl is not produced nor maintained by the\nFree Software Foundation. Perl's licensing terms are also more open than\nGNU software's tend to be.\n\nYou can get commercial support of Perl if you wish, although for most\nusers the informal support will more than suffice. See the answer to\n\"Where can I buy a commercial version of Perl?\" for more information.\n\nWhich version of Perl should I use?\n(contributed by brian d foy with updates from others)\n\nThere is often a matter of opinion and taste, and there isn't any one\nanswer that fits everyone. In general, you want to use either the\ncurrent stable release, or the stable release immediately prior to that\none.\n\nBeyond that, you have to consider several things and decide which is\nbest for you.\n\n*   If things aren't broken, upgrading perl may break them (or at least\nissue new warnings).\n\n*   The latest versions of perl have more bug fixes.\n\n*   The latest versions of perl may contain performance improvements and\nfeatures not present in older versions. There have been many changes\nin perl since perl5 was first introduced.\n\n*   The Perl community is geared toward supporting the most recent\nreleases, so you'll have an easier time finding help for those.\n\n*   Older versions of perl may have security vulnerabilities, some of\nwhich are serious (see perlsec and search CVEs\n<https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=Perl> for more\ninformation).\n\n*   The latest versions are probably the least deployed and widely\ntested, so you may want to wait a few months after their release and\nsee what problems others have if you are risk averse.\n\n*   The immediate, in addition to the current stable release, the\nprevious stable release is maintained. See \"MAINTENANCE AND SUPPORT\"\nin perlpolicy for more information.\n\n*   There are really two tracks of perl development: a maintenance\nversion and an experimental version. The maintenance versions are\nstable, and have an even number as the minor release (i.e.\nperl5.24.x, where 24 is the minor release). The experimental\nversions may include features that don't make it into the stable\nversions, and have an odd number as the minor release (i.e.\nperl5.25.x, where 25 is the minor release).\n\n*   You can consult releases <http://dev.perl.org/perl5> to determine\nthe current stable release of Perl.\n\nWhat are Perl 4, Perl 5, or Raku (Perl 6)?\nIn short, Perl 4 is the parent to both Perl 5 and Raku (formerly known\nas Perl 6). Perl 5 is the older sibling, and though they are different\nlanguages, someone who knows one will spot many similarities in the\nother.\n\nThe number after Perl (i.e. the 5 after Perl 5) is the major release of\nthe perl interpreter as well as the version of the language. Each major\nversion has significant differences that earlier versions cannot\nsupport.\n\nThe current major release of Perl is Perl 5, first released in 1994. It\ncan run scripts from the previous major release, Perl 4 (March 1991),\nbut has significant differences.\n\nRaku is a reinvention of Perl, a language in the same lineage but not\ncompatible. The two are complementary, not mutually exclusive. Raku is\nnot meant to replace Perl, and vice versa. See \"What is Raku (Perl 6)?\"\nbelow to find out more.\n\nSee perlhist for a history of Perl revisions.\n\nWhat is Raku (Perl 6)?\nRaku (formerly known as Perl 6) was *originally* described as the\ncommunity's rewrite of Perl, however as the language evolved, it became\nclear that it is a separate language, but in the same language family as\nPerl.\n\nRaku is not intended primarily as a replacement for Perl, but as its own\nthing - and libraries exist to allow you to call Perl code from Raku\nprograms and vice versa.\n\nContrary to popular belief, Raku and Perl peacefully coexist with one\nanother. Raku has proven to be a fascinating source of ideas for those\nusing Perl (the Moose object system is a well-known example). There is\noverlap in the communities, and this overlap fosters the tradition of\nsharing and borrowing that have been instrumental to Perl's success.\n\nFor more about Raku see <https://www.raku.org/>.\n\n\"We're really serious about reinventing everything that needs\nreinventing.\" --Larry Wall\n\nHow stable is Perl?\nProduction releases, which incorporate bug fixes and new functionality,\nare widely tested before release. Since the 5.000 release, we have\naveraged about one production release per year.\n\nThe Perl development team occasionally make changes to the internal core\nof the language, but all possible efforts are made toward backward\ncompatibility.\n\nHow often are new versions of Perl released?\nRecently, the plan has been to release a new version of Perl roughly\nevery April, but getting the release right is more important than\nsticking rigidly to a calendar date, so the release date is somewhat\nflexible. The historical release dates can be viewed at\n<http://www.cpan.org/src/README.html>.\n\nEven numbered minor versions (5.14, 5.16, 5.18) are production versions,\nand odd numbered minor versions (5.15, 5.17, 5.19) are development\nversions. Unless you want to try out an experimental feature, you\nprobably never want to install a development version of Perl.\n\nThe Perl development team are called Perl 5 Porters, and their\norganization is described at <http://perldoc.perl.org/perlpolicy.html>.\nThe organizational rules really just boil down to one: Larry is always\nright, even when he was wrong.\n\nIs Perl difficult to learn?\nNo, Perl is easy to start learning <http://learn.perl.org/> --and easy\nto keep learning. It looks like most programming languages you're likely\nto have experience with, so if you've ever written a C program, an awk\nscript, a shell script, or even a BASIC program, you're already partway\nthere.\n\nMost tasks only require a small subset of the Perl language. One of the\nguiding mottos for Perl development is \"there's more than one way to do\nit\" (TMTOWTDI, sometimes pronounced \"tim toady\"). Perl's learning curve\nis therefore shallow (easy to learn) and long (there's a whole lot you\ncan do if you really want).\n\nFinally, because Perl is frequently (but not always, and certainly not\nby definition) an interpreted language, you can write your programs and\ntest them without an intermediate compilation step, allowing you to\nexperiment and test/debug quickly and easily. This ease of\nexperimentation flattens the learning curve even more.\n\nThings that make Perl easier to learn: Unix experience, almost any kind\nof programming experience, an understanding of regular expressions, and\nthe ability to understand other people's code. If there's something you\nneed to do, then it's probably already been done, and a working example\nis usually available for free. Don't forget Perl modules, either.\nThey're discussed in Part 3 of this FAQ, along with CPAN\n<http://www.cpan.org/>, which is discussed in Part 2.\n\nHow does Perl compare with other languages like Java, Python, REXX, Scheme, or Tcl?\nPerl can be used for almost any coding problem, even ones which require\nintegrating specialist C code for extra speed. As with any tool it can\nbe used well or badly. Perl has many strengths, and a few weaknesses,\nprecisely which areas are good and bad is often a personal choice.\n\nWhen choosing a language you should also be influenced by the resources\n<http://www.cpan.org/>, testing culture <http://www.cpantesters.org/>\nand community <http://www.perl.org/community.html> which surrounds it.\n\nFor comparisons to a specific language it is often best to create a\nsmall project in both languages and compare the results, make sure to\nuse all the resources <http://www.cpan.org/> of each language, as a\nlanguage is far more than just it's syntax.\n\nCan I do [task] in Perl?\nPerl is flexible and extensible enough for you to use on virtually any\ntask, from one-line file-processing tasks to large, elaborate systems.\n\nFor many people, Perl serves as a great replacement for shell scripting.\nFor others, it serves as a convenient, high-level replacement for most\nof what they'd program in low-level languages like C or C++. It's\nultimately up to you (and possibly your management) which tasks you'll\nuse Perl for and which you won't.\n\nIf you have a library that provides an API, you can make any component\nof it available as just another Perl function or variable using a Perl\nextension written in C or C++ and dynamically linked into your main perl\ninterpreter. You can also go the other direction, and write your main\nprogram in C or C++, and then link in some Perl code on the fly, to\ncreate a powerful application. See perlembed.\n\nThat said, there will always be small, focused, special-purpose\nlanguages dedicated to a specific problem domain that are simply more\nconvenient for certain kinds of problems. Perl tries to be all things to\nall people, but nothing special to anyone. Examples of specialized\nlanguages that come to mind include prolog and matlab.\n\nWhen shouldn't I program in Perl?\nOne good reason is when you already have an existing application written\nin another language that's all done (and done well), or you have an\napplication language specifically designed for a certain task (e.g.\nprolog, make).\n\nIf you find that you need to speed up a specific part of a Perl\napplication (not something you often need) you may want to use C, but\nyou can access this from your Perl code with perlxs.\n\nWhat's the difference between \"perl\" and \"Perl\"?\n\"Perl\" is the name of the language. Only the \"P\" is capitalized. The\nname of the interpreter (the program which runs the Perl script) is\n\"perl\" with a lowercase \"p\".\n\nYou may or may not choose to follow this usage. But never write \"PERL\",\nbecause perl is not an acronym.\n\nHow can I convince others to use Perl?\n(contributed by brian d foy)\n\nAppeal to their self interest! If Perl is new (and thus scary) to them,\nfind something that Perl can do to solve one of their problems. That\nmight mean that Perl either saves them something (time, headaches,\nmoney) or gives them something (flexibility, power, testability).\n\nIn general, the benefit of a language is closely related to the skill of\nthe people using that language. If you or your team can be faster,\nbetter, and stronger through Perl, you'll deliver more value. Remember,\npeople often respond better to what they get out of it. If you run into\nresistance, figure out what those people get out of the other choice and\nhow Perl might satisfy that requirement.\n\nYou don't have to worry about finding or paying for Perl; it's freely\navailable and several popular operating systems come with Perl.\nCommunity support in places such as Perlmonks (\n<http://www.perlmonks.com> ) and the various Perl mailing lists (\n<http://lists.perl.org> ) means that you can usually get quick answers\nto your problems.\n\nFinally, keep in mind that Perl might not be the right tool for every\njob. You're a much better advocate if your claims are reasonable and\ngrounded in reality. Dogmatically advocating anything tends to make\npeople discount your message. Be honest about possible disadvantages to\nyour choice of Perl since any choice has trade-offs.\n\nYou might find these links useful:\n\n*   <http://www.perl.org/about.html>\n\n*   <http://perltraining.com.au/whyperl.html>\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq2.pod": {
            "content": "What machines support Perl? Where do I get it?\nThe standard release of Perl (the one maintained by the Perl development\nteam) is distributed only in source code form. You can find the latest\nreleases at <http://www.cpan.org/src/>.\n\nPerl builds and runs on a bewildering number of platforms. Virtually all\nknown and current Unix derivatives are supported (perl's native\nplatform), as are other systems like VMS, DOS, OS/2, Windows, QNX, BeOS,\nOS X, MPE/iX and the Amiga.\n\nBinary distributions for some proprietary platforms can be found\n<http://www.cpan.org/ports/> directory. Because these are not part of\nthe standard distribution, they may and in fact do differ from the base\nperl port in a variety of ways. You'll have to check their respective\nrelease notes to see just what the differences are. These differences\ncan be either positive (e.g. extensions for the features of the\nparticular platform that are not supported in the source release of\nperl) or negative (e.g. might be based upon a less current source\nrelease of perl).\n\nHow can I get a binary version of Perl?\nSee CPAN Ports <http://www.cpan.org/ports/>\n\nI don't have a C compiler. How can I build my own Perl interpreter?\nFor Windows, use a binary version of Perl, Strawberry Perl\n<http://strawberryperl.com/> and ActivePerl\n<http://www.activestate.com/activeperl> come with a bundled C compiler.\n\nOtherwise if you really do want to build Perl, you need to get a binary\nversion of \"gcc\" for your system first. Use a search engine to find out\nhow to do this for your operating system.\n\nI copied the Perl binary from one machine to another, but scripts don't work.\nThat's probably because you forgot libraries, or library paths differ.\nYou really should build the whole distribution on the machine it will\neventually live on, and then type \"make install\". Most other approaches\nare doomed to failure.\n\nOne simple way to check that things are in the right place is to print\nout the hard-coded @INC that perl looks through for libraries:\n\n% perl -le 'print for @INC'\n\nIf this command lists any paths that don't exist on your system, then\nyou may need to move the appropriate libraries to these locations, or\ncreate symbolic links, aliases, or shortcuts appropriately. @INC is also\nprinted as part of the output of\n\n% perl -V\n\nYou might also want to check out \"How do I keep my own module/library\ndirectory?\" in perlfaq8.\n\nI grabbed the sources and tried to compile but gdbm/dynamic loading/malloc/linking/... failed. How do I make it work?\nRead the INSTALL file, which is part of the source distribution. It\ndescribes in detail how to cope with most idiosyncrasies that the\n\"Configure\" script can't work around for any given system or\narchitecture.\n\nWhat modules and extensions are available for Perl? What is CPAN?\nCPAN stands for Comprehensive Perl Archive Network, a multi-gigabyte\narchive replicated on hundreds of machines all over the world. CPAN\ncontains tens of thousands of modules and extensions, source code and\ndocumentation, designed for *everything* from commercial database\ninterfaces to keyboard/screen control and running large web sites.\n\nYou can search CPAN on <http://metacpan.org>.\n\nThe master web site for CPAN is <http://www.cpan.org/>,\n<http://www.cpan.org/SITES.html> lists all mirrors.\n\nSee the CPAN FAQ at <http://www.cpan.org/misc/cpan-faq.html> for answers\nto the most frequently asked questions about CPAN.\n\nThe Task::Kensho module has a list of recommended modules which you\nshould review as a good starting point.\n\nWhere can I get information on Perl?\n*   <http://www.perl.org/>\n\n*   <http://perldoc.perl.org/>\n\n*   <http://learn.perl.org/>\n\nThe complete Perl documentation is available with the Perl distribution.\nIf you have Perl installed locally, you probably have the documentation\ninstalled as well: type \"perldoc perl\" in a terminal or view online\n<http://perldoc.perl.org/perl.html>.\n\n(Some operating system distributions may ship the documentation in a\ndifferent package; for instance, on Debian, you need to install the\n\"perl-doc\" package.)\n\nMany good books have been written about Perl--see the section later in\nperlfaq2 for more details.\n\nWhat is perl.com? Perl Mongers? pm.org? perl.org? cpan.org?\nPerl.com <http://www.perl.com/> used to be part of the O'Reilly Network,\na subsidiary of O'Reilly Media. Although it retains most of the original\ncontent from its O'Reilly Network, it is now hosted by The Perl\nFoundation <http://www.perlfoundation.org/>.\n\nThe Perl Foundation is an advocacy organization for the Perl language\nwhich maintains the web site <http://www.perl.org/> as a general\nadvocacy site for the Perl language. It uses the domain to provide\ngeneral support services to the Perl community, including the hosting of\nmailing lists, web sites, and other services. There are also many other\nsub-domains for special topics like learning Perl and jobs in Perl, such\nas:\n\n*   <http://www.perl.org/>\n\n*   <http://learn.perl.org/>\n\n*   <http://jobs.perl.org/>\n\n*   <http://lists.perl.org/>\n\nPerl Mongers <http://www.pm.org/> uses the pm.org domain for services\nrelated to local Perl user groups, including the hosting of mailing\nlists and web sites. See the Perl Mongers web site <http://www.pm.org/>\nfor more information about joining, starting, or requesting services for\na Perl user group.\n\nCPAN, or the Comprehensive Perl Archive Network <http://www.cpan.org/>,\nis a replicated, worldwide repository of Perl software. See What is\nCPAN?.\n",
            "subsections": [
                {
                    "name": "Perl Books",
                    "content": "There are many good books on Perl\n<http://www.perl.org/books/library.html>.\n\nWhich magazines have Perl content?\nThere's also *$foo Magazin*, a German magazine dedicated to Perl, at (\n<http://www.foo-magazin.de> ). The *Perl-Zeitung* is another\nGerman-speaking magazine for Perl beginners (see\n<http://perl-zeitung.at.tf> ).\n\nSeveral Unix/Linux related magazines frequently include articles on\nPerl.\n\nWhich Perl blogs should I read?\nPerl News <http://perlnews.org/> covers some of the major events in the\nPerl world, Perl Weekly <http://perlweekly.com/> is a weekly e-mail (and\nRSS feed) of hand-picked Perl articles.\n\n<http://blogs.perl.org/> hosts many Perl blogs, there are also several\nblog aggregators: Perlsphere <http://perlsphere.net/> and IronMan\n<http://ironman.enlightenedperl.org/> are two of them.\n\nWhat mailing lists are there for Perl?\nA comprehensive list of Perl-related mailing lists can be found at\n<http://lists.perl.org/>\n\nWhere can I buy a commercial version of Perl?\nPerl already *is* commercial software: it has a license that you can\ngrab and carefully read to your manager. It is distributed in releases\nand comes in well-defined packages. There is a very large and supportive\nuser community and an extensive literature.\n\nIf you still need commercial support ActiveState\n<http://www.activestate.com/activeperl> offers this.\n"
                }
            ]
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq3.pod": {
            "content": "How can I use Perl interactively?\nThe typical approach uses the Perl debugger, described in the",
            "subsections": [
                {
                    "name": "perldebug",
                    "content": "perl -de 42\n\nNow just type in any legal Perl code, and it will be immediately\nevaluated. You can also examine the symbol table, get stack backtraces,\ncheck variable values, set breakpoints, and other operations typically\nfound in symbolic debuggers.\n\nYou can also use Devel::REPL which is an interactive shell for Perl,\ncommonly known as a REPL - Read, Evaluate, Print, Loop. It provides\nvarious handy features.\n\nHow do I find which modules are installed on my system?\nFrom the command line, you can use the \"cpan\" command's \"-l\" switch:\n\n$ cpan -l\n\nYou can also use \"cpan\"'s \"-a\" switch to create an autobundle file that\n\"CPAN.pm\" understands and can use to re-install every module:\n\n$ cpan -a\n\nInside a Perl program, you can use the ExtUtils::Installed module to\nshow all installed distributions, although it can take awhile to do its\nmagic. The standard library which comes with Perl just shows up as\n\"Perl\" (although you can get those with Module::CoreList).\n\nuse ExtUtils::Installed;\n\nmy $inst    = ExtUtils::Installed->new();\nmy @modules = $inst->modules();\n\nIf you want a list of all of the Perl module filenames, you can use\nFile::Find::Rule:\n\nuse File::Find::Rule;\n\nmy @files = File::Find::Rule->\nextras({follow => 1})->\nfile()->\nname( '*.pm' )->\nin( @INC )\n;\n\nIf you do not have that module, you can do the same thing with\nFile::Find which is part of the standard library:\n\nuse File::Find;\nmy @files;\n\nfind(\n{\nwanted => sub {\npush @files, $File::Find::fullname\nif -f $File::Find::fullname && /\\.pm$/\n},\nfollow => 1,\nfollowskip => 2,\n},\n@INC\n);\n\nprint join \"\\n\", @files;\n\nIf you simply need to check quickly to see if a module is available, you\ncan check for its documentation. If you can read the documentation the\nmodule is most likely installed. If you cannot read the documentation,\nthe module might not have any (in rare cases):\n\n$ perldoc Module::Name\n\nYou can also try to include the module in a one-liner to see if perl\nfinds it:\n\n$ perl -MModule::Name -e1\n\n(If you don't receive a \"Can't locate ... in @INC\" error message, then\nPerl found the module name you asked for.)\n\nHow do I debug my Perl programs?\n(contributed by brian d foy)\n\nBefore you do anything else, you can help yourself by ensuring that you\nlet Perl tell you about problem areas in your code. By turning on\nwarnings and strictures, you can head off many problems before they get\ntoo big. You can find out more about these in strict and warnings.\n\n#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nBeyond that, the simplest debugger is the \"print\" function. Use it to\nlook at values as you run your program:\n\nprint STDERR \"The value is [$value]\\n\";\n\nThe Data::Dumper module can pretty-print Perl data structures:\n\nuse Data::Dumper qw( Dumper );\nprint STDERR \"The hash is \" . Dumper( \\%hash ) . \"\\n\";\n\nPerl comes with an interactive debugger, which you can start with the\n\"-d\" switch. It's fully explained in perldebug.\n\nIf you'd like a graphical user interface and you have Tk, you can use\n\"ptkdb\". It's on CPAN and available for free.\n\nIf you need something much more sophisticated and controllable, Leon\nBrocard's Devel::ebug (which you can call with the \"-D\" switch as\n\"-Debug\") gives you the programmatic hooks into everything you need to\nwrite your own (without too much pain and suffering).\n\nYou can also use a commercial debugger such as Affrus (Mac OS X), Komodo\nfrom Activestate (Windows and Mac OS X), or EPIC (most platforms).\n\nHow do I profile my Perl programs?\n(contributed by brian d foy, updated Fri Jul 25 12:22:26 PDT 2008)\n\nThe \"Devel\" namespace has several modules which you can use to profile\nyour Perl programs.\n\nThe Devel::NYTProf (New York Times Profiler) does both statement and\nsubroutine profiling. It's available from CPAN and you also invoke it\nwith the \"-d\" switch:\n\nperl -d:NYTProf someperl.pl\n\nIt creates a database of the profile information that you can turn into\nreports. The \"nytprofhtml\" command turns the data into an HTML report\nsimilar to the Devel::Cover report:\n\nnytprofhtml\n\nYou might also be interested in using the Benchmark to measure and\ncompare code snippets.\n\nYou can read more about profiling in *Programming Perl*, chapter 20, or\n*Mastering Perl*, chapter 5.\n\nperldebguts documents creating a custom debugger if you need to create a\nspecial sort of profiler. brian d foy describes the process in *The Perl\nJournal*, \"Creating a Perl Debugger\", <http://www.ddj.com/184404522> ,\nand \"Profiling in Perl\" <http://www.ddj.com/184404580> .\n\nPerl.com has two interesting articles on profiling: \"Profiling Perl\", by\nSimon Cozens, <https://www.perl.com/pub/2004/06/25/profiling.html/> and\n\"Debugging and Profiling modperl Applications\", by Frank Wiles,\n<http://www.perl.com/pub/a/2006/02/09/debugmodperl.html> .\n\nRandal L. Schwartz writes about profiling in \"Speeding up Your Perl\nPrograms\" for *Unix Review*,\n<http://www.stonehenge.com/merlyn/UnixReview/col49.html> , and\n\"Profiling in Template Toolkit via Overriding\" for *Linux Magazine*,\n<http://www.stonehenge.com/merlyn/LinuxMag/col75.html> .\n\nHow do I cross-reference my Perl programs?\nThe B::Xref module can be used to generate cross-reference reports for\nPerl programs.\n\nperl -MO=Xref[,OPTIONS] scriptname.plx\n\nIs there a pretty-printer (formatter) for Perl?\nPerl::Tidy comes with a perl script perltidy which indents and reformats\nPerl scripts to make them easier to read by trying to follow the rules\nof the perlstyle. If you write Perl, or spend much time reading Perl,\nyou will probably find it useful.\n\nOf course, if you simply follow the guidelines in perlstyle, you\nshouldn't need to reformat. The habit of formatting your code as you\nwrite it will help prevent bugs. Your editor can and should help you\nwith this. The perl-mode or newer cperl-mode for emacs can provide\nremarkable amounts of help with most (but not all) code, and even less\nprogrammable editors can provide significant assistance. Tom\nChristiansen and many other VI users swear by the following settings in\nvi and its clones:\n\nset ai sw=4\nmap! ^O {^M}^[O^T\n\nPut that in your .exrc file (replacing the caret characters with control\ncharacters) and away you go. In insert mode, ^T is for indenting, ^D is\nfor undenting, and ^O is for blockdenting--as it were. A more complete\nexample, with comments, can be found at\n<http://www.cpan.org/authors/id/T/TO/TOMC/scripts/toms.exrc.gz>\n\nIs there an IDE or Windows Perl Editor?\nPerl programs are just plain text, so any editor will do.\n\nIf you're on Unix, you already have an IDE--Unix itself. The Unix\nphilosophy is the philosophy of several small tools that each do one\nthing and do it well. It's like a carpenter's toolbox.\n\nIf you want an IDE, check the following (in alphabetical order, not\norder of preference):\n\nEclipse\n<http://e-p-i-c.sf.net/>\n\nThe Eclipse Perl Integration Project integrates Perl\nediting/debugging with Eclipse.\n\nEnginsite\n<http://www.enginsite.com/>\n\nPerl Editor by EngInSite is a complete integrated development\nenvironment (IDE) for creating, testing, and debugging Perl scripts;\nthe tool runs on Windows 9x/NT/2000/XP or later.\n\nIntelliJ IDEA\n<https://plugins.jetbrains.com/plugin/7796>\n\nCamelcade plugin provides Perl5 support in IntelliJ IDEA and other\nJetBrains IDEs.\n\nKephra\n<http://kephra.sf.net>\n\nGUI editor written in Perl using wxWidgets and Scintilla with lots\nof smaller features. Aims for a UI based on Perl principles like\nTIMTOWTDI and \"easy things should be easy, hard things should be\npossible\".\n\nKomodo\n<http://www.ActiveState.com/Products/Komodo/>\n\nActiveState's cross-platform (as of October 2004, that's Windows,\nLinux, and Solaris), multi-language IDE has Perl support, including\na regular expression debugger and remote debugging.\n\nNotepad++\n<http://notepad-plus.sourceforge.net/>\n\nOpen Perl IDE\n<http://open-perl-ide.sourceforge.net/>\n\nOpen Perl IDE is an integrated development environment for writing\nand debugging Perl scripts with ActiveState's ActivePerl\ndistribution under Windows 95/98/NT/2000.\n\nOptiPerl\n<http://www.optiperl.com/>\n\nOptiPerl is a Windows IDE with simulated CGI environment, including\ndebugger and syntax-highlighting editor.\n\nPadre\n<http://padre.perlide.org/>\n\nPadre is cross-platform IDE for Perl written in Perl using wxWidgets\nto provide a native look and feel. It's open source under the\nArtistic License. It is one of the newer Perl IDEs.\n\nPerlBuilder\n<http://www.solutionsoft.com/perl.htm>\n\nPerlBuilder is an integrated development environment for Windows\nthat supports Perl development.\n\nvisiPerl+\n<http://helpconsulting.net/visiperl/index.html>\n\nFrom Help Consulting, for Windows.\n\nVisual Perl\n<http://www.activestate.com/Products/VisualPerl/>\n\nVisual Perl is a Visual Studio.NET plug-in from ActiveState.\n\nZeus\n<http://www.zeusedit.com/lookmain.html>\n\nZeus for Windows is another Win32 multi-language editor/IDE that\ncomes with support for Perl.\n\nFor editors: if you're on Unix you probably have vi or a vi clone\nalready, and possibly an emacs too, so you may not need to download\nanything. In any emacs the cperl-mode (M-x cperl-mode) gives you perhaps\nthe best available Perl editing mode in any editor.\n\nIf you are using Windows, you can use any editor that lets you work with\nplain text, such as NotePad or WordPad. Word processors, such as\nMicrosoft Word or WordPerfect, typically do not work since they insert\nall sorts of behind-the-scenes information, although some allow you to\nsave files as \"Text Only\". You can also download text editors designed\nspecifically for programming, such as Textpad (\n<http://www.textpad.com/> ) and UltraEdit ( <http://www.ultraedit.com/>\n), among others.\n\nIf you are using MacOS, the same concerns apply. MacPerl (for Classic\nenvironments) comes with a simple editor. Popular external editors are\nBBEdit ( <http://www.barebones.com/products/bbedit/> ) or Alpha (\n<http://www.his.com/~jguyer/Alpha/Alpha8.html> ). MacOS X users can use\nUnix editors as well.\n\nGNU Emacs\n<http://www.gnu.org/software/emacs/windows/ntemacs.html>\n\nMicroEMACS\n<http://www.microemacs.de/>\n\nXEmacs\n<http://www.xemacs.org/Download/index.html>\n\nJed <http://space.mit.edu/~davis/jed/>\n\nor a vi clone such as\n\nVim <http://www.vim.org/>\n\nVile\n<http://invisible-island.net/vile/vile.html>\n\nThe following are Win32 multilanguage editor/IDEs that support Perl:\n\nMultiEdit\n<http://www.MultiEdit.com/>\n\nSlickEdit\n<http://www.slickedit.com/>\n\nConTEXT\n<http://www.contexteditor.org/>\n\nThere is also a toyedit Text widget based editor written in Perl that is\ndistributed with the Tk module on CPAN. The ptkdb (\n<http://ptkdb.sourceforge.net/> ) is a Perl/Tk-based debugger that acts\nas a development environment of sorts. Perl Composer (\n<http://perlcomposer.sourceforge.net/> ) is an IDE for Perl/Tk GUI\ncreation.\n\nIn addition to an editor/IDE you might be interested in a more powerful\nshell environment for Win32. Your options include\n\nbash\nfrom the Cygwin package ( <http://cygwin.com/> )\n\nzsh <http://www.zsh.org/>\n\nCygwin is covered by the GNU General Public License (but that shouldn't\nmatter for Perl use). Cygwin contains (in addition to the shell) a\ncomprehensive set of standard Unix toolkit utilities.\n\nBBEdit and TextWrangler\nare text editors for OS X that have a Perl sensitivity mode (\n<http://www.barebones.com/> ).\n\nWhere can I get Perl macros for vi?\nFor a complete version of Tom Christiansen's vi configuration file, see\n<http://www.cpan.org/authors/id/T/TO/TOMC/scripts/toms.exrc.gz> , the\nstandard benchmark file for vi emulators. The file runs best with nvi,\nthe current version of vi out of Berkeley, which incidentally can be\nbuilt with an embedded Perl interpreter--see\n<http://www.cpan.org/src/misc/> .\n\nWhere can I get perl-mode or cperl-mode for emacs?\nSince Emacs version 19 patchlevel 22 or so, there have been both a\nperl-mode.el and support for the Perl debugger built in. These should\ncome with the standard Emacs 19 distribution.\n\nNote that the perl-mode of emacs will have fits with \"main'foo\" (single\nquote), and mess up the indentation and highlighting. You are probably\nusing \"main::foo\" in new Perl code anyway, so this shouldn't be an\nissue.\n\nFor CPerlMode, see <http://www.emacswiki.org/cgi-bin/wiki/CPerlMode>\n\nHow can I use curses with Perl?\nThe Curses module from CPAN provides a dynamically loadable object\nmodule interface to a curses library. A small demo can be found at the\ndirectory <http://www.cpan.org/authors/id/T/TO/TOMC/scripts/rep.gz> ;\nthis program repeats a command and updates the screen as needed,\nrendering rep ps axu similar to top.\n\nHow can I write a GUI (X, Tk, Gtk, etc.) in Perl?\n(contributed by Ben Morrow)\n\nThere are a number of modules which let you write GUIs in Perl. Most GUI\ntoolkits have a perl interface: an incomplete list follows.\n\nTk  This works under Unix and Windows, and the current version doesn't\nlook half as bad under Windows as it used to. Some of the gui\nelements still don't 'feel' quite right, though. The interface is\nvery natural and 'perlish', making it easy to use in small scripts\nthat just need a simple gui. It hasn't been updated in a while.\n\nWx  This is a Perl binding for the cross-platform wxWidgets toolkit (\n<http://www.wxwidgets.org> ). It works under Unix, Win32 and Mac OS\nX, using native widgets (Gtk under Unix). The interface follows the\nC++ interface closely, but the documentation is a little sparse for\nsomeone who doesn't know the library, mostly just referring you to\nthe C++ documentation.\n\nGtk and Gtk2\nThese are Perl bindings for the Gtk toolkit ( <http://www.gtk.org>\n). The interface changed significantly between versions 1 and 2 so\nthey have separate Perl modules. It runs under Unix, Win32 and Mac\nOS X (currently it requires an X server on Mac OS, but a 'native'\nport is underway), and the widgets look the same on every platform:\ni.e., they don't match the native widgets. As with Wx, the Perl\nbindings follow the C API closely, and the documentation requires\nyou to read the C documentation to understand it.\n\nWin32::GUI\nThis provides access to most of the Win32 GUI widgets from Perl.\nObviously, it only runs under Win32, and uses native widgets. The\nPerl interface doesn't really follow the C interface: it's been made\nmore Perlish, and the documentation is pretty good. More advanced\nstuff may require familiarity with the C Win32 APIs, or reference to\nMSDN.\n\nCamelBones\nCamelBones ( <http://camelbones.sourceforge.net> ) is a Perl\ninterface to Mac OS X's Cocoa GUI toolkit, and as such can be used\nto produce native GUIs on Mac OS X. It's not on CPAN, as it requires\nframeworks that CPAN.pm doesn't know how to install, but\ninstallation is via the standard OSX package installer. The Perl API\nis, again, very close to the ObjC API it's wrapping, and the\ndocumentation just tells you how to translate from one to the other.\n\nQt  There is a Perl interface to TrollTech's Qt toolkit, but it does not\nappear to be maintained.\n\nAthena\nSx is an interface to the Athena widget set which comes with X, but\nagain it appears not to be much used nowadays.\n\nHow can I make my Perl program run faster?\nThe best way to do this is to come up with a better algorithm. This can\noften make a dramatic difference. Jon Bentley's book *Programming\nPearls* (that's not a misspelling!) has some good tips on optimization,\ntoo. Advice on benchmarking boils down to: benchmark and profile to make\nsure you're optimizing the right part, look for better algorithms\ninstead of microtuning your code, and when all else fails consider just\nbuying faster hardware. You will probably want to read the answer to the\nearlier question \"How do I profile my Perl programs?\" if you haven't\ndone so already.\n\nA different approach is to autoload seldom-used Perl code. See the\nAutoSplit and AutoLoader modules in the standard distribution for that.\nOr you could locate the bottleneck and think about writing just that\npart in C, the way we used to take bottlenecks in C code and write them\nin assembler. Similar to rewriting in C, modules that have critical\nsections can be written in C (for instance, the PDL module from CPAN).\n\nIf you're currently linking your perl executable to a shared *libc.so*,\nyou can often gain a 10-25% performance benefit by rebuilding it to link\nwith a static libc.a instead. This will make a bigger perl executable,\nbut your Perl programs (and programmers) may thank you for it. See the\nINSTALL file in the source distribution for more information.\n\nThe undump program was an ancient attempt to speed up Perl program by\nstoring the already-compiled form to disk. This is no longer a viable\noption, as it only worked on a few architectures, and wasn't a good\nsolution anyway.\n\nHow can I make my Perl program take less memory?\nWhen it comes to time-space tradeoffs, Perl nearly always prefers to\nthrow memory at a problem. Scalars in Perl use more memory than strings\nin C, arrays take more than that, and hashes use even more. While\nthere's still a lot to be done, recent releases have been addressing\nthese issues. For example, as of 5.004, duplicate hash keys are shared\namongst all hashes using them, so require no reallocation.\n\nIn some cases, using substr() or vec() to simulate arrays can be highly\nbeneficial. For example, an array of a thousand booleans will take at\nleast 20,000 bytes of space, but it can be turned into one 125-byte bit\nvector--a considerable memory savings. The standard Tie::SubstrHash\nmodule can also help for certain types of data structure. If you're\nworking with specialist data structures (matrices, for instance) modules\nthat implement these in C may use less memory than equivalent Perl\nmodules.\n\nAnother thing to try is learning whether your Perl was compiled with the\nsystem malloc or with Perl's builtin malloc. Whichever one it is, try\nusing the other one and see whether this makes a difference. Information\nabout malloc is in the INSTALL file in the source distribution. You can\nfind out whether you are using perl's malloc by typing \"perl\n-V:usemymalloc\".\n\nOf course, the best way to save memory is to not do anything to waste it\nin the first place. Good programming practices can go a long way toward\nthis:\n\nDon't slurp!\nDon't read an entire file into memory if you can process it line by\nline. Or more concretely, use a loop like this:\n\n#\n# Good Idea\n#\nwhile (my $line = <$filehandle>) {\n# ...\n}\n\ninstead of this:\n\n#\n# Bad Idea\n#\nmy @data = <$filehandle>;\nforeach (@data) {\n# ...\n}\n\nWhen the files you're processing are small, it doesn't much matter\nwhich way you do it, but it makes a huge difference when they start\ngetting larger.\n\nUse map and grep selectively\nRemember that both map and grep expect a LIST argument, so doing\nthis:\n\n@wanted = grep {/pattern/} <$filehandle>;\n\nwill cause the entire file to be slurped. For large files, it's\nbetter to loop:\n\nwhile (<$filehandle>) {\npush(@wanted, $) if /pattern/;\n}\n\nAvoid unnecessary quotes and stringification\nDon't quote large strings unless absolutely necessary:\n\nmy $copy = \"$largestring\";\n\nmakes 2 copies of $largestring (one for $copy and another for the\nquotes), whereas\n\nmy $copy = $largestring;\n\nonly makes one copy.\n\nDitto for stringifying large arrays:\n\n{\nlocal $, = \"\\n\";\nprint @bigarray;\n}\n\nis much more memory-efficient than either\n\nprint join \"\\n\", @bigarray;\n\nor\n\n{\nlocal $\" = \"\\n\";\nprint \"@bigarray\";\n}\n\nPass by reference\nPass arrays and hashes by reference, not by value. For one thing,\nit's the only way to pass multiple lists or hashes (or both) in a\nsingle call/return. It also avoids creating a copy of all the\ncontents. This requires some judgement, however, because any changes\nwill be propagated back to the original data. If you really want to\nmangle (er, modify) a copy, you'll have to sacrifice the memory\nneeded to make one.\n\nTie large variables to disk\nFor \"big\" data stores (i.e. ones that exceed available memory)\nconsider using one of the DB modules to store it on disk instead of\nin RAM. This will incur a penalty in access time, but that's\nprobably better than causing your hard disk to thrash due to massive\nswapping.\n\nIs it safe to return a reference to local or lexical data?\nYes. Perl's garbage collection system takes care of this so everything\nworks out right.\n\nsub makeone {\nmy @a = ( 1 .. 10 );\nreturn \\@a;\n}\n\nfor ( 1 .. 10 ) {\npush @many, makeone();\n}\n\nprint $many[4][5], \"\\n\";\n\nprint \"@many\\n\";\n\nHow can I hide the source for my Perl program?\nDelete it. :-) Seriously, there are a number of (mostly unsatisfactory)\nsolutions with varying levels of \"security\".\n\nFirst of all, however, you *can't* take away read permission, because\nthe source code has to be readable in order to be compiled and\ninterpreted. (That doesn't mean that a CGI script's source is readable\nby people on the web, though--only by people with access to the\nfilesystem.) So you have to leave the permissions at the socially\nfriendly 0755 level.\n\nSome people regard this as a security problem. If your program does\ninsecure things and relies on people not knowing how to exploit those\ninsecurities, it is not secure. It is often possible for someone to\ndetermine the insecure things and exploit them without viewing the\nsource. Security through obscurity, the name for hiding your bugs\ninstead of fixing them, is little security indeed.\n\nYou can try using encryption via source filters (Starting from Perl 5.8\nthe Filter::Simple and Filter::Util::Call modules are included in the\nstandard distribution), but any decent programmer will be able to\ndecrypt it. You can try using the byte code compiler and interpreter\ndescribed later in perlfaq3, but the curious might still be able to\nde-compile it. You can try using the native-code compiler described\nlater, but crackers might be able to disassemble it. These pose varying\ndegrees of difficulty to people wanting to get at your code, but none\ncan definitively conceal it (true of every language, not just Perl).\n\nIt is very easy to recover the source of Perl programs. You simply feed\nthe program to the perl interpreter and use the modules in the B::\nhierarchy. The B::Deparse module should be able to defeat most attempts\nto hide source. Again, this is not unique to Perl.\n\nIf you're concerned about people profiting from your code, then the\nbottom line is that nothing but a restrictive license will give you\nlegal security. License your software and pepper it with threatening\nstatements like \"This is unpublished proprietary software of XYZ Corp.\nYour access to it does not give you permission to use it blah blah\nblah.\" We are not lawyers, of course, so you should see a lawyer if you\nwant to be sure your license's wording will stand up in court.\n\nHow can I compile my Perl program into byte code or C?\n(contributed by brian d foy)\n\nIn general, you can't do this. There are some things that may work for\nyour situation though. People usually ask this question because they\nwant to distribute their works without giving away the source code, and\nmost solutions trade disk space for convenience. You probably won't see\nmuch of a speed increase either, since most solutions simply bundle a\nPerl interpreter in the final product (but see \"How can I make my Perl\nprogram run faster?\").\n\nThe Perl Archive Toolkit is Perl's analog to Java's JAR. It's freely\navailable and on CPAN ( <https://metacpan.org/pod/PAR> ).\n\nThere are also some commercial products that may work for you, although\nyou have to buy a license for them.\n\nThe Perl Dev Kit ( <http://www.activestate.com/Products/PerlDevKit/> )\nfrom ActiveState can \"Turn your Perl programs into ready-to-run\nexecutables for HP-UX, Linux, Solaris and Windows.\"\n\nPerl2Exe ( <http://www.indigostar.com/perl2exe.htm> ) is a command line\nprogram for converting perl scripts to executable files. It targets both\nWindows and Unix platforms.\n\nHow can I get \"#!perl\" to work on [MS-DOS,NT,...]?\nFor OS/2 just use\n\nextproc perl -S -yourswitches\n\nas the first line in \"*.cmd\" file (\"-S\" due to a bug in cmd.exe's\n\"extproc\" handling). For DOS one should first invent a corresponding\nbatch file and codify it in \"ALTERNATESHEBANG\" (see the dosish.h file\nin the source distribution for more information).\n\nThe Win95/NT installation, when using the ActiveState port of Perl, will\nmodify the Registry to associate the \".pl\" extension with the perl\ninterpreter. If you install another port, perhaps even building your own\nWin95/NT Perl from the standard sources by using a Windows port of gcc\n(e.g., with cygwin or mingw32), then you'll have to modify the Registry\nyourself. In addition to associating \".pl\" with the interpreter, NT\npeople can use: \"SET PATHEXT=%PATHEXT%;.PL\" to let them run the program\n\"install-linux.pl\" merely by typing \"install-linux\".\n\nUnder \"Classic\" MacOS, a perl program will have the appropriate Creator\nand Type, so that double-clicking them will invoke the MacPerl\napplication. Under Mac OS X, clickable apps can be made from any \"#!\"\nscript using Wil Sanchez' DropScript utility:\n<http://www.wsanchez.net/software/> .\n\n*IMPORTANT!*: Whatever you do, PLEASE don't get frustrated, and just\nthrow the perl interpreter into your cgi-bin directory, in order to get\nyour programs working for a web server. This is an EXTREMELY big\nsecurity risk. Take the time to figure out how to do it correctly.\n\nCan I write useful Perl programs on the command line?\nYes. Read perlrun for more information. Some examples follow. (These\nassume standard Unix shell quoting rules.)\n\n# sum first and last fields\nperl -lane 'print $F[0] + $F[-1]' *\n\n# identify text files\nperl -le 'for(@ARGV) {print if -f && -T }' *\n\n# remove (most) comments from C program\nperl -0777 -pe 's{/\\*.*?\\*/}{}gs' foo.c\n\n# make file a month younger than today, defeating reaper daemons\nperl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *\n\n# find first unused uid\nperl -le '$i++ while getpwuid($i); print $i'\n\n# display reasonable manpath\necho $PATH | perl -nl -072 -e '\ns![^/+]*$!man!&&-d&&!$s{$}++&&push@m,$;END{print\"@m\"}'\n\nOK, the last one was actually an Obfuscated Perl Contest entry. :-)\n\nWhy don't Perl one-liners work on my DOS/Mac/VMS system?\nThe problem is usually that the command interpreters on those systems\nhave rather different ideas about quoting than the Unix shells under\nwhich the one-liners were created. On some systems, you may have to\nchange single-quotes to double ones, which you must *NOT* do on Unix or\nPlan9 systems. You might also have to change a single % to a %%.\n\nFor example:\n\n# Unix (including Mac OS X)\nperl -e 'print \"Hello world\\n\"'\n\n# DOS, etc.\nperl -e \"print \\\"Hello world\\n\\\"\"\n\n# Mac Classic\nprint \"Hello world\\n\"\n(then Run \"Myscript\" or Shift-Command-R)\n\n# MPW\nperl -e 'print \"Hello world\\n\"'\n\n# VMS\nperl -e \"print \"\"Hello world\\n\"\"\"\n\nThe problem is that none of these examples are reliable: they depend on\nthe command interpreter. Under Unix, the first two often work. Under\nDOS, it's entirely possible that neither works. If 4DOS was the command\nshell, you'd probably have better luck like this:\n\nperl -e \"print <Ctrl-x>\"Hello world\\n<Ctrl-x>\"\"\n\nUnder the Mac, it depends which environment you are using. The MacPerl\nshell, or MPW, is much like Unix shells in its support for several\nquoting variants, except that it makes free use of the Mac's non-ASCII\ncharacters as control characters.\n\nUsing qq(), q(), and qx(), instead of \"double quotes\", 'single quotes',\nand `backticks`, may make one-liners easier to write.\n\nThere is no general solution to all of this. It is a mess.\n\n[Some of this answer was contributed by Kenneth Albanowski.]\n\nWhere can I learn about CGI or Web programming in Perl?\nFor modules, get the CGI or LWP modules from CPAN. For textbooks, see\nthe two especially dedicated to web stuff in the question on books. For\nproblems and questions related to the web, like \"Why do I get 500\nErrors\" or \"Why doesn't it run from the browser right when it runs fine\non the command line\", see the troubleshooting guides and references in\nperlfaq9 or in the CGI MetaFAQ:\n\nL<http://www.perl.org/CGIMetaFAQ.html>\n\nLooking into <https://plackperl.org> and modern Perl web frameworks is\nhighly recommended, though; web programming in Perl has evolved a long\nway from the old days of simple CGI scripts.\n\nWhere can I learn about object-oriented Perl programming?\nA good place to start is perlootut, and you can use perlobj for\nreference.\n\nA good book on OO on Perl is the \"Object-Oriented Perl\" by Damian Conway\nfrom Manning Publications, or \"Intermediate Perl\" by Randal Schwartz,\nbrian d foy, and Tom Phoenix from O'Reilly Media.\n\nWhere can I learn about linking C with Perl?\nIf you want to call C from Perl, start with perlxstut, moving on to\nperlxs, xsubpp, and perlguts. If you want to call Perl from C, then read\nperlembed, perlcall, and perlguts. Don't forget that you can learn a lot\nfrom looking at how the authors of existing extension modules wrote\ntheir code and solved their problems.\n\nYou might not need all the power of XS. The Inline::C module lets you\nput C code directly in your Perl source. It handles all the magic to\nmake it work. You still have to learn at least some of the perl API but\nyou won't have to deal with the complexity of the XS support files.\n\nI've read perlembed, perlguts, etc., but I can't embed perl in my C program; what am I doing wrong?\nDownload the ExtUtils::Embed kit from CPAN and run `make test'. If the\ntests pass, read the pods again and again and again. If they fail,\nsubmit a bug report to <https://github.com/Perl/perl5/issues> with the\noutput of \"make test TESTVERBOSE=1\" along with \"perl -V\".\n"
                }
            ]
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq4.pod": {
            "content": "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?\nFor the long explanation, see David Goldberg's \"What Every Computer\nScientist Should Know About Floating-Point Arithmetic\"\n(<http://web.cse.msu.edu/~cse320/Documents/FloatingPoint.pdf>).\n\nInternally, your computer represents floating-point numbers in binary.\nDigital (as in powers of two) computers cannot store all numbers\nexactly. Some real numbers lose precision in the process. This is a\nproblem with how computers store numbers and affects all computer\nlanguages, not just Perl.\n\nperlnumber shows the gory details of number representations and\nconversions.\n\nTo limit the number of decimal places in your numbers, you can use the\n\"printf\" or \"sprintf\" function. See \"Floating-point Arithmetic\" in\nperlop for more details.\n\nprintf \"%.2f\", 10/3;\n\nmy $number = sprintf \"%.2f\", 10/3;\n\nWhy isn't my octal data interpreted correctly?\n(contributed by brian d foy)\n\nYou're probably trying to convert a string to a number, which Perl only\nconverts as a decimal number. When Perl converts a string to a number,\nit ignores leading spaces and zeroes, then assumes the rest of the\ndigits are in base 10:\n\nmy $string = '0644';\n\nprint $string + 0;  # prints 644\n\nprint $string + 44; # prints 688, certainly not octal!\n\nThis problem usually involves one of the Perl built-ins that has the\nsame name a Unix command that uses octal numbers as arguments on the\ncommand line. In this example, \"chmod\" on the command line knows that\nits first argument is octal because that's what it does:\n\n%prompt> chmod 644 file\n\nIf you want to use the same literal digits (644) in Perl, you have to\ntell Perl to treat them as octal numbers either by prefixing the digits\nwith a 0 or using \"oct\":\n\nchmod(     0644, $filename );  # right, has leading zero\nchmod( oct(644), $filename );  # also correct\n\nThe problem comes in when you take your numbers from something that Perl\nthinks is a string, such as a command line argument in @ARGV:\n\nchmod( $ARGV[0],      $filename );  # wrong, even if \"0644\"\n\nchmod( oct($ARGV[0]), $filename );  # correct, treat string as octal\n\nYou can always check the value you're using by printing it in octal\nnotation to ensure it matches what you think it should be. Print it in\noctal and decimal format:\n\nprintf \"0%o %d\", $number, $number;\n\nDoes Perl have a round() function? What about ceil() and floor()? Trig functions?\nRemember that int() merely truncates toward 0. For rounding to a certain\nnumber of digits, sprintf() or printf() is usually the easiest route.\n\nprintf(\"%.3f\", 3.1415926535);   # prints 3.142\n\nThe POSIX module (part of the standard Perl distribution) implements",
            "subsections": [
                {
                    "name": "ceil",
                    "content": "functions.\n\nuse POSIX;\nmy $ceil   = ceil(3.5);   # 4\nmy $floor  = floor(3.5);  # 3\n\nIn 5.000 to 5.003 perls, trigonometry was done in the Math::Complex\nmodule. With 5.004, the Math::Trig module (part of the standard Perl\ndistribution) implements the trigonometric functions. Internally it uses\nthe Math::Complex module and some functions can break out from the real\naxis into the complex plane, for example the inverse sine of 2.\n\nRounding in financial applications can have serious implications, and\nthe rounding method used should be specified precisely. In these cases,\nit probably pays not to trust whichever system of rounding is being used\nby Perl, but instead to implement the rounding function you need\nyourself.\n\nTo see why, notice how you'll still have an issue on half-way-point\nalternation:\n\nfor (my $i = -5; $i <= 5; $i += 0.5) { printf \"%.0f \",$i }\n\n-5 -4 -4 -4 -3 -2 -2 -2 -1 -0 0 0 1 2 2 2 3 4 4 4 5\n\nDon't blame Perl. It's the same as in C. IEEE says we have to do this.\nPerl numbers whose absolute values are integers under 231 (on 32-bit\nmachines) will work pretty much like mathematical integers. Other\nnumbers are not guaranteed.\n\nHow do I multiply matrices?\nUse the Math::Matrix or Math::MatrixReal modules (available from CPAN)\nor the PDL extension (also available from CPAN).\n\nHow can I output Roman numerals?\nGet the <http://www.cpan.org/modules/by-module/Roman> module.\n\nHow do I find the current century or millennium?\nUse the following simple functions:\n\nsub getcentury    {\nreturn int((((localtime(shift || time))[5] + 1999))/100);\n}\n\nsub getmillennium {\nreturn 1+int((((localtime(shift || time))[5] + 1899))/1000);\n}\n\nOn some systems, the POSIX module's strftime() function has been\nextended in a non-standard way to use a %C format, which they sometimes\nclaim is the \"century\". It isn't, because on most such systems, this is\nonly the first two digits of the four-digit year, and thus cannot be\nused to determine reliably the current century or millennium.\n\nHow can I find the Julian Day?\n(contributed by brian d foy and Dave Cross)\n\nYou can use the Time::Piece module, part of the Standard Library, which\ncan convert a date/time to a Julian Day:\n\n$ perl -MTime::Piece -le 'print localtime->julianday'\n2455607.7959375\n\nOr the modified Julian Day:\n\n$ perl -MTime::Piece -le 'print localtime->mjd'\n55607.2961226851\n\nOr even the day of the year (which is what some people think of as a\nJulian day):\n\n$ perl -MTime::Piece -le 'print localtime->yday'\n45\n\nYou can also do the same things with the DateTime module:\n\n$ perl -MDateTime -le'print DateTime->today->jd'\n2453401.5\n$ perl -MDateTime -le'print DateTime->today->mjd'\n53401\n$ perl -MDateTime -le'print DateTime->today->doy'\n31\n\nYou can use the Time::JulianDay module available on CPAN. Ensure that\nyou really want to find a Julian day, though, as many people have\ndifferent ideas about Julian days (see\n<http://www.hermetic.ch/calstud/jdn.htm> for instance):\n\n$  perl -MTime::JulianDay -le 'print localjulianday( time )'\n55608\n\nDoes Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?\n(contributed by brian d foy)\n\nPerl itself never had a Y2K problem, although that never stopped people\nfrom creating Y2K problems on their own. See the documentation for\n\"localtime\" for its proper use.\n\nStarting with Perl 5.12, \"localtime\" and \"gmtime\" can handle dates past\n03:14:08 January 19, 2038, when a 32-bit based time would overflow. You\nstill might get a warning on a 32-bit \"perl\":\n\n% perl5.12 -E 'say scalar localtime( 0x9FFFFFFFFFFF )'\nInteger overflow in hexadecimal number at -e line 1.\nWed Nov  1 19:42:39 5576711\n\nOn a 64-bit \"perl\", you can get even larger dates for those really long\nrunning projects:\n\n% perl5.12 -E 'say scalar gmtime( 0x9FFFFFFFFFFF )'\nThu Nov  2 00:42:39 5576711\n\nYou're still out of luck if you need to keep track of decaying protons\nthough.\n\nHow do I validate input?\n(contributed by brian d foy)\n\nThere are many ways to ensure that values are what you expect or want to\naccept. Besides the specific examples that we cover in the perlfaq, you\ncan also look at the modules with \"Assert\" and \"Validate\" in their\nnames, along with other modules such as Regexp::Common.\n\nSome modules have validation for particular types of input, such as\nBusiness::ISBN, Business::CreditCard, Email::Valid, and\nData::Validate::IP.\n\nHow do I expand function calls in a string?\n(contributed by brian d foy)\n\nThis is documented in perlref, and although it's not the easiest thing\nto read, it does work. In each of these examples, we call the function\ninside the braces used to dereference a reference. If we have more than\none return value, we can construct and dereference an anonymous array.\nIn this case, we call the function in list context.\n\nprint \"The time values are @{ [localtime] }.\\n\";\n\nIf we want to call the function in scalar context, we have to do a bit\nmore work. We can really have any code we like inside the braces, so we\nsimply have to end with the scalar reference, although how you do that\nis up to you, and you can use code inside the braces. Note that the use\nof parens creates a list context, so we need \"scalar\" to force the\nscalar context on the function:\n\nprint \"The time is ${\\(scalar localtime)}.\\n\"\n\nprint \"The time is ${ my $x = localtime; \\$x }.\\n\";\n\nIf your function already returns a reference, you don't need to create\nthe reference yourself.\n\nsub timestamp { my $t = localtime; \\$t }\n\nprint \"The time is ${ timestamp() }.\\n\";\n\nThe \"Interpolation\" module can also do a lot of magic for you. You can\nspecify a variable name, in this case \"E\", to set up a tied hash that\ndoes the interpolation for you. It has several other methods to do this\nas well.\n\nuse Interpolation E => 'eval';\nprint \"The time values are $E{localtime()}.\\n\";\n\nIn most cases, it is probably easier to simply use string concatenation,\nwhich also forces scalar context.\n\nprint \"The time is \" . localtime() . \".\\n\";\n\nHow do I capitalize all the words on one line?\n(contributed by brian d foy)\n\nDamian Conway's Text::Autoformat handles all of the thinking for you.\n\nuse Text::Autoformat;\nmy $x = \"Dr. Strangelove or: How I Learned to Stop \".\n\"Worrying and Love the Bomb\";\n\nprint $x, \"\\n\";\nfor my $style (qw( sentence title highlight )) {\nprint autoformat($x, { case => $style }), \"\\n\";\n}\n\nHow do you want to capitalize those words?\n\nFRED AND BARNEY'S LODGE        # all uppercase\nFred And Barney's Lodge        # title case\nFred and Barney's Lodge        # highlight case\n\nIt's not as easy a problem as it looks. How many words do you think are\nin there? Wait for it... wait for it.... If you answered 5 you're right.\nPerl words are groups of \"\\w+\", but that's not what you want to\ncapitalize. How is Perl supposed to know not to capitalize that \"s\"\nafter the apostrophe? You could try a regular expression:\n\n$string =~ s/ (\n(^\\w)    #at the beginning of the line\n|      # or\n(\\s\\w)   #preceded by whitespace\n)\n/\\U$1/xg;\n\n$string =~ s/([\\w']+)/\\u\\L$1/g;\n\nNow, what if you don't want to capitalize that \"and\"? Just use\nText::Autoformat and get on with the next problem. :)\n\nHow can I split a [character]-delimited string except when inside [character]?\nSeveral modules can handle this sort of parsing--Text::Balanced,\nText::CSV, Text::CSVXS, and Text::ParseWords, among others.\n\nTake the example case of trying to split a string that is\ncomma-separated into its different fields. You can't use \"split(/,/)\"\nbecause you shouldn't split if the comma is inside quotes. For example,\ntake a data line like this:\n\nSAR001,\"\",\"Cimetrix, Inc\",\"Bob Smith\",\"CAM\",N,8,1,0,7,\"Error, Core Dumped\"\n\nDue to the restriction of the quotes, this is a fairly complex problem.\nThankfully, we have Jeffrey Friedl, author of *Mastering Regular\nExpressions*, to handle these for us. He suggests (assuming your string\nis contained in $text):\n\nmy @new = ();\npush(@new, $+) while $text =~ m{\n\"([^\\\"\\\\]*(?:\\\\.[^\\\"\\\\]*)*)\",? # groups the phrase inside the quotes\n| ([^,]+),?\n| ,\n}gx;\npush(@new, undef) if substr($text,-1,1) eq ',';\n\nIf you want to represent quotation marks inside a\nquotation-mark-delimited field, escape them with backslashes (eg, \"like\n\\\"this\\\"\".\n\nAlternatively, the Text::ParseWords module (part of the standard Perl\ndistribution) lets you say:\n\nuse Text::ParseWords;\n@new = quotewords(\",\", 0, $text);\n\nFor parsing or generating CSV, though, using Text::CSV rather than\nimplementing it yourself is highly recommended; you'll save yourself odd\nbugs popping up later by just using code which has already been tried\nand tested in production for years.\n\nHow do I strip blank space from the beginning/end of a string?\n(contributed by brian d foy)\n\nA substitution can do this for you. For a single line, you want to\nreplace all the leading or trailing whitespace with nothing. You can do\nthat with a pair of substitutions:\n\ns/^\\s+//;\ns/\\s+$//;\n\nYou can also write that as a single substitution, although it turns out\nthe combined statement is slower than the separate ones. That might not\nmatter to you, though:\n\ns/^\\s+|\\s+$//g;\n\nIn this regular expression, the alternation matches either at the\nbeginning or the end of the string since the anchors have a lower\nprecedence than the alternation. With the \"/g\" flag, the substitution\nmakes all possible matches, so it gets both. Remember, the trailing\nnewline matches the \"\\s+\", and the \"$\" anchor can match to the absolute\nend of the string, so the newline disappears too. Just add the newline\nto the output, which has the added benefit of preserving \"blank\"\n(consisting entirely of whitespace) lines which the \"^\\s+\" would remove\nall by itself:\n\nwhile( <> ) {\ns/^\\s+|\\s+$//g;\nprint \"$\\n\";\n}\n\nFor a multi-line string, you can apply the regular expression to each\nlogical line in the string by adding the \"/m\" flag (for \"multi-line\").\nWith the \"/m\" flag, the \"$\" matches *before* an embedded newline, so it\ndoesn't remove it. This pattern still removes the newline at the end of\nthe string:\n\n$string =~ s/^\\s+|\\s+$//gm;\n\nRemember that lines consisting entirely of whitespace will disappear,\nsince the first part of the alternation can match the entire string and\nreplace it with nothing. If you need to keep embedded blank lines, you\nhave to do a little more work. Instead of matching any whitespace (since\nthat includes a newline), just match the other whitespace:\n\n$string =~ s/^[\\t\\f ]+|[\\t\\f ]+$//mg;\n\nHow do I pad a string with blanks or pad a number with zeroes?\nIn the following examples, $padlen is the length to which you wish to\npad the string, $text or $num contains the string to be padded, and\n$padchar contains the padding character. You can use a single character\nstring constant instead of the $padchar variable if you know what it is\nin advance. And in the same way you can use an integer in place of\n$padlen if you know the pad length in advance.\n\nThe simplest method uses the \"sprintf\" function. It can pad on the left\nor right with blanks and on the left with zeroes and it will not\ntruncate the result. The \"pack\" function can only pad strings on the\nright with blanks and it will truncate the result to a maximum length of\n$padlen.\n\n# Left padding a string with blanks (no truncation):\nmy $padded = sprintf(\"%${padlen}s\", $text);\nmy $padded = sprintf(\"%*s\", $padlen, $text);  # same thing\n\n# Right padding a string with blanks (no truncation):\nmy $padded = sprintf(\"%-${padlen}s\", $text);\nmy $padded = sprintf(\"%-*s\", $padlen, $text); # same thing\n\n# Left padding a number with 0 (no truncation):\nmy $padded = sprintf(\"%0${padlen}d\", $num);\nmy $padded = sprintf(\"%0*d\", $padlen, $num); # same thing\n\n# Right padding a string with blanks using pack (will truncate):\nmy $padded = pack(\"A$padlen\",$text);\n\nIf you need to pad with a character other than blank or zero you can use\none of the following methods. They all generate a pad string with the\n\"x\" operator and combine that with $text. These methods do not truncate\n$text.\n\nLeft and right padding with any character, creating a new string:\n\nmy $padded = $padchar x ( $padlen - length( $text ) ) . $text;\nmy $padded = $text . $padchar x ( $padlen - length( $text ) );\n\nLeft and right padding with any character, modifying $text directly:\n\nsubstr( $text, 0, 0 ) = $padchar x ( $padlen - length( $text ) );\n$text .= $padchar x ( $padlen - length( $text ) );\n\nHow do I extract selected columns from a string?\n(contributed by brian d foy)\n\nIf you know the columns that contain the data, you can use \"substr\" to\nextract a single column.\n\nmy $column = substr( $line, $startcolumn, $length );\n\nYou can use \"split\" if the columns are separated by whitespace or some\nother delimiter, as long as whitespace or the delimiter cannot appear as\npart of the data.\n\nmy $line    = ' fred barney   betty   ';\nmy @columns = split /\\s+/, $line;\n# ( '', 'fred', 'barney', 'betty' );\n\nmy $line    = 'fred||barney||betty';\nmy @columns = split /\\|/, $line;\n# ( 'fred', '', 'barney', '', 'betty' );\n\nIf you want to work with comma-separated values, don't do this since\nthat format is a bit more complicated. Use one of the modules that\nhandle that format, such as Text::CSV, Text::CSVXS, or Text::CSVPP.\n\nIf you want to break apart an entire line of fixed columns, you can use\n\"unpack\" with the A (ASCII) format. By using a number after the format\nspecifier, you can denote the column width. See the \"pack\" and \"unpack\"\nentries in perlfunc for more details.\n\nmy @fields = unpack( $line, \"A8 A8 A8 A16 A4\" );\n\nNote that spaces in the format argument to \"unpack\" do not denote\nliteral spaces. If you have space separated data, you may want \"split\"\ninstead.\n\nHow do I find the soundex value of a string?\n(contributed by brian d foy)\n\nYou can use the \"Text::Soundex\" module. If you want to do fuzzy or close\nmatching, you might also try the String::Approx, and Text::Metaphone,\nand Text::DoubleMetaphone modules.\n\nHow can I expand variables in text strings?\n(contributed by brian d foy)\n\nIf you can avoid it, don't, or if you can use a templating system, such\nas Text::Template or Template Toolkit, do that instead. You might even\nbe able to get the job done with \"sprintf\" or \"printf\":\n\nmy $string = sprintf 'Say hello to %s and %s', $foo, $bar;\n\nHowever, for the one-off simple case where I don't want to pull out a\nfull templating system, I'll use a string that has two Perl scalar\nvariables in it. In this example, I want to expand $foo and $bar to\ntheir variable's values:\n\nmy $foo = 'Fred';\nmy $bar = 'Barney';\n$string = 'Say hello to $foo and $bar';\n\nOne way I can do this involves the substitution operator and a double\n\"/e\" flag. The first \"/e\" evaluates $1 on the replacement side and turns\nit into $foo. The second /e starts with $foo and replaces it with its\nvalue. $foo, then, turns into 'Fred', and that's finally what's left in\nthe string:\n\n$string =~ s/(\\$\\w+)/$1/eeg; # 'Say hello to Fred and Barney'\n\nThe \"/e\" will also silently ignore violations of strict, replacing\nundefined variable names with the empty string. Since I'm using the \"/e\"\nflag (twice even!), I have all of the same security problems I have with\n\"eval\" in its string form. If there's something odd in $foo, perhaps\nsomething like \"@{[ system \"rm -rf /\" ]}\", then I could get myself in\ntrouble.\n\nTo get around the security problem, I could also pull the values from a\nhash instead of evaluating variable names. Using a single \"/e\", I can\ncheck the hash to ensure the value exists, and if it doesn't, I can\nreplace the missing value with a marker, in this case \"???\" to signal\nthat I missed something:\n\nmy $string = 'This has $foo and $bar';\n\nmy %Replacements = (\nfoo  => 'Fred',\n);\n\n# $string =~ s/\\$(\\w+)/$Replacements{$1}/g;\n$string =~ s/\\$(\\w+)/\nexists $Replacements{$1} ? $Replacements{$1} : '???'\n/eg;\n\nprint $string;\n\nDoes Perl have anything like Ruby's #{} or Python's f string?\nUnlike the others, Perl allows you to embed a variable naked in a double\nquoted string, e.g. \"variable $variable\". When there isn't whitespace or\nother non-word characters following the variable name, you can add\nbraces (e.g. \"foo ${foo}bar\") to ensure correct parsing.\n\nAn array can also be embedded directly in a string, and will be expanded\nby default with spaces between the elements. The default LISTSEPARATOR\ncan be changed by assigning a different string to the special variable\n$\", such as \"local $\" = ', ';\".\n\nPerl also supports references within a string providing the equivalent\nof the features in the other two languages.\n\n\"${\\ ... }\" embedded within a string will work for most simple\nstatements such as an object->method call. More complex code can be\nwrapped in a do block \"${\\ do{...} }\".\n\nWhen you want a list to be expanded per $\", use \"@{[ ... ]}\".\n\nuse Time::Piece;\nuse Time::Seconds;\nmy $scalar = 'STRING';\nmy @array = ( 'zorro', 'a', 1, 'B', 3 );\n\n# Print the current date and time and then Tommorrow\nmy $t = Time::Piece->new;\nsay \"Now is: ${\\ $t->cdate() }\";\nsay \"Tomorrow: ${\\ do{ my $T=Time::Piece->new + ONEDAY ; $T->fullday }}\";\n\n# some variables in strings\nsay \"This is some scalar I have $scalar, this is an array @array.\";\nsay \"You can also write it like this ${scalar} @{array}.\";\n\n# Change the $LISTSEPARATOR\nlocal $\" = ':';\nsay \"Set \\$\\\" to delimit with ':' and sort the Array @{[ sort @array ]}\";\n\nYou may also want to look at the module Quote::Code, and templating\ntools such as Template::Toolkit and Mojo::Template.\n\nSee also: \"How can I expand variables in text strings?\" and \"How do I\nexpand function calls in a string?\" in this FAQ.\n\nWhat's wrong with always quoting \"$vars\"?\nThe problem is that those double-quotes force stringification--coercing\nnumbers and references into strings--even when you don't want them to be\nstrings. Think of it this way: double-quote expansion is used to produce\nnew strings. If you already have a string, why do you need more?\n\nIf you get used to writing odd things like these:\n\nprint \"$var\";       # BAD\nmy $new = \"$old\";       # BAD\nsomefunc(\"$var\");    # BAD\n\nYou'll be in trouble. Those should (in 99.8% of the cases) be the\nsimpler and more direct:\n\nprint $var;\nmy $new = $old;\nsomefunc($var);\n\nOtherwise, besides slowing you down, you're going to break code when the\nthing in the scalar is actually neither a string nor a number, but a\nreference:\n\nfunc(\\@array);\nsub func {\nmy $aref = shift;\nmy $oref = \"$aref\";  # WRONG\n}\n\nYou can also get into subtle problems on those few operations in Perl\nthat actually do care about the difference between a string and a\nnumber, such as the magical \"++\" autoincrement operator or the syscall()\nfunction.\n\nStringification also destroys arrays.\n\nmy @lines = `command`;\nprint \"@lines\";     # WRONG - extra blanks\nprint @lines;       # right\n\nWhy don't my <<HERE documents work?\nHere documents are found in perlop. Check for these three things:\n\nThere must be no space after the << part.\nThere (probably) should be a semicolon at the end of the opening token\nYou can't (easily) have any space in front of the tag.\nThere needs to be at least a line separator after the end token.\n\nIf you want to indent the text in the here document, you can do this:\n\n# all in one\n(my $VAR = <<HERETARGET) =~ s/^\\s+//gm;\nyour text\ngoes here\nHERETARGET\n\nBut the HERETARGET must still be flush against the margin. If you want\nthat indented also, you'll have to quote in the indentation.\n\n(my $quote = <<'    FINIS') =~ s/^\\s+//gm;\n...we will have peace, when you and all your works have\nperished--and the works of your dark master to whom you\nwould deliver us. You are a liar, Saruman, and a corrupter\nof men's hearts. --Theoden in /usr/src/perl/taint.c\nFINIS\n$quote =~ s/\\s+--/\\n--/;\n\nA nice general-purpose fixer-upper function for indented here documents\nfollows. It expects to be called with a here document as its argument.\nIt looks to see whether each line begins with a common substring, and if\nso, strips that substring off. Otherwise, it takes the amount of leading\nwhitespace found on the first line and removes that much off each\nsubsequent line.\n\nsub fix {\nlocal $ = shift;\nmy ($white, $leader);  # common whitespace and common leading string\nif (/^\\s*(?:([^\\w\\s]+)(\\s*).*\\n)(?:\\s*\\g1\\g2?.*\\n)+$/) {\n($white, $leader) = ($2, quotemeta($1));\n} else {\n($white, $leader) = (/^(\\s+)/, '');\n}\ns/^\\s*?$leader(?:$white)?//gm;\nreturn $;\n}\n\nThis works with leading special strings, dynamically determined:\n\nmy $rememberthemain = fix<<'    MAININTERPRETERLOOP';\n@@@ int\n@@@ runops() {\n@@@     SAVEI32(runlevel);\n@@@     runlevel++;\n@@@     while ( op = (*op->opppaddr)() );\n@@@     TAINTNOT;\n@@@     return 0;\n@@@ }\nMAININTERPRETERLOOP\n\nOr with a fixed amount of leading whitespace, with remaining indentation\ncorrectly preserved:\n\nmy $poem = fix<<EVERONANDON;\nNow far ahead the Road has gone,\nAnd I must follow, if I can,\nPursuing it with eager feet,\nUntil it joins some larger way\nWhere many paths and errands meet.\nAnd whither then? I cannot say.\n--Bilbo in /usr/src/perl/ppctl.c\nEVERONANDON\n\nBeginning with Perl version 5.26, a much simpler and cleaner way to\nwrite indented here documents has been added to the language: the tilde\n(~) modifier. See \"Indented Here-docs\" in perlop for details.\n\nWhat is the difference between a list and an array?\n(contributed by brian d foy)\n\nA list is a fixed collection of scalars. An array is a variable that\nholds a variable collection of scalars. An array can supply its\ncollection for list operations, so list operations also work on arrays:\n\n# slices\n( 'dog', 'cat', 'bird' )[2,3];\n@animals[2,3];\n\n# iteration\nforeach ( qw( dog cat bird ) ) { ... }\nforeach ( @animals ) { ... }\n\nmy @three = grep { length == 3 } qw( dog cat bird );\nmy @three = grep { length == 3 } @animals;\n\n# supply an argument list\nwashanimals( qw( dog cat bird ) );\nwashanimals( @animals );\n\nArray operations, which change the scalars, rearrange them, or add or\nsubtract some scalars, only work on arrays. These can't work on a list,\nwhich is fixed. Array operations include \"shift\", \"unshift\", \"push\",\n\"pop\", and \"splice\".\n\nAn array can also change its length:\n\n$#animals = 1;  # truncate to two elements\n$#animals = 10000; # pre-extend to 10,001 elements\n\nYou can change an array element, but you can't change a list element:\n\n$animals[0] = 'Rottweiler';\nqw( dog cat bird )[0] = 'Rottweiler'; # syntax error!\n\nforeach ( @animals ) {\ns/^d/fr/;  # works fine\n}\n\nforeach ( qw( dog cat bird ) ) {\ns/^d/fr/;  # Error! Modification of read only value!\n}\n\nHowever, if the list element is itself a variable, it appears that you\ncan change a list element. However, the list element is the variable,\nnot the data. You're not changing the list element, but something the\nlist element refers to. The list element itself doesn't change: it's\nstill the same variable.\n\nYou also have to be careful about context. You can assign an array to a\nscalar to get the number of elements in the array. This only works for\narrays, though:\n\nmy $count = @animals;  # only works with arrays\n\nIf you try to do the same thing with what you think is a list, you get a\nquite different result. Although it looks like you have a list on the\nrighthand side, Perl actually sees a bunch of scalars separated by a\ncomma:\n\nmy $scalar = ( 'dog', 'cat', 'bird' );  # $scalar gets bird\n\nSince you're assigning to a scalar, the righthand side is in scalar\ncontext. The comma operator (yes, it's an operator!) in scalar context\nevaluates its lefthand side, throws away the result, and evaluates it's\nrighthand side and returns the result. In effect, that list-lookalike\nassigns to $scalar it's rightmost value. Many people mess this up\nbecause they choose a list-lookalike whose last element is also the\ncount they expect:\n\nmy $scalar = ( 1, 2, 3 );  # $scalar gets 3, accidentally\n\nHow can I remove duplicate elements from a list or array?\n(contributed by brian d foy)\n\nUse a hash. When you think the words \"unique\" or \"duplicated\", think\n\"hash keys\".\n\nIf you don't care about the order of the elements, you could just create\nthe hash then extract the keys. It's not important how you create that\nhash: just that you use \"keys\" to get the unique elements.\n\nmy %hash   = map { $, 1 } @array;\n# or a hash slice: @hash{ @array } = ();\n# or a foreach: $hash{$} = 1 foreach ( @array );\n\nmy @unique = keys %hash;\n\nIf you want to use a module, try the \"uniq\" function from\nList::MoreUtils. In list context it returns the unique elements,\npreserving their order in the list. In scalar context, it returns the\nnumber of unique elements.\n\nuse List::MoreUtils qw(uniq);\n\nmy @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7\nmy $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7\n\nYou can also go through each element and skip the ones you've seen\nbefore. Use a hash to keep track. The first time the loop sees an\nelement, that element has no key in %Seen. The \"next\" statement creates\nthe key and immediately uses its value, which is \"undef\", so the loop\ncontinues to the \"push\" and increments the value for that key. The next\ntime the loop sees that same element, its key exists in the hash *and*\nthe value for that key is true (since it's not 0 or \"undef\"), so the\nnext skips that iteration and the loop goes to the next element.\n\nmy @unique = ();\nmy %seen   = ();\n\nforeach my $elem ( @array ) {\nnext if $seen{ $elem }++;\npush @unique, $elem;\n}\n\nYou can write this more briefly using a grep, which does the same thing.\n\nmy %seen = ();\nmy @unique = grep { ! $seen{ $ }++ } @array;\n\nHow can I tell whether a certain element is contained in a list or array?\n(portions of this answer contributed by Anno Siegel and brian d foy)\n\nHearing the word \"in\" is an *in*dication that you probably should have\nused a hash, not a list or array, to store your data. Hashes are\ndesigned to answer this question quickly and efficiently. Arrays aren't.\n\nThat being said, there are several ways to approach this. If you are\ngoing to make this query many times over arbitrary string values, the\nfastest way is probably to invert the original array and maintain a hash\nwhose keys are the first array's values:\n\nmy @blues = qw/azure cerulean teal turquoise lapis-lazuli/;\nmy %isblue = ();\nfor (@blues) { $isblue{$} = 1 }\n\nNow you can check whether $isblue{$somecolor}. It might have been a\ngood idea to keep the blues all in a hash in the first place.\n\nIf the values are all small integers, you could use a simple indexed\narray. This kind of an array will take up less space:\n\nmy @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);\nmy @istinyprime = ();\nfor (@primes) { $istinyprime[$] = 1 }\n# or simply  @istinyprime[@primes] = (1) x @primes;\n\nNow you check whether $istinyprime[$somenumber].\n\nIf the values in question are integers instead of strings, you can save\nquite a lot of space by using bit strings instead:\n\nmy @articles = ( 1..10, 150..2000, 2017 );\nundef $read;\nfor (@articles) { vec($read,$,1) = 1 }\n\nNow check whether \"vec($read,$n,1)\" is true for some $n.\n\nThese methods guarantee fast individual tests but require a\nre-organization of the original list or array. They only pay off if you\nhave to test multiple values against the same array.\n\nIf you are testing only once, the standard module List::Util exports the\nfunction \"any\" for this purpose. It works by stopping once it finds the\nelement. It's written in C for speed, and its Perl equivalent looks like\nthis subroutine:\n\nsub any (&@) {\nmy $code = shift;\nforeach (@) {\nreturn 1 if $code->();\n}\nreturn 0;\n}\n\nIf speed is of little concern, the common idiom uses grep in scalar\ncontext (which returns the number of items that passed its condition) to\ntraverse the entire list. This does have the benefit of telling you how\nmany matches it found, though.\n\nmy $isthere = grep $ eq $whatever, @array;\n\nIf you want to actually extract the matching elements, simply use grep\nin list context.\n\nmy @matches = grep $ eq $whatever, @array;\n\nHow do I test whether two arrays or hashes are equal?\nThe following code works for single-level arrays. It uses a stringwise\ncomparison, and does not distinguish defined versus undefined empty\nstrings. Modify if you have other needs.\n\n$areequal = comparearrays(\\@frogs, \\@toads);\n\nsub comparearrays {\nmy ($first, $second) = @;\nno warnings;  # silence spurious -w undef complaints\nreturn 0 unless @$first == @$second;\nfor (my $i = 0; $i < @$first; $i++) {\nreturn 0 if $first->[$i] ne $second->[$i];\n}\nreturn 1;\n}\n\nFor multilevel structures, you may wish to use an approach more like\nthis one. It uses the CPAN module FreezeThaw:\n\nuse FreezeThaw qw(cmpStr);\nmy @a = my @b = ( \"this\", \"that\", [ \"more\", \"stuff\" ] );\n\nprintf \"a and b contain %s arrays\\n\",\ncmpStr(\\@a, \\@b) == 0\n? \"the same\"\n: \"different\";\n\nThis approach also works for comparing hashes. Here we'll demonstrate\ntwo different answers:\n\nuse FreezeThaw qw(cmpStr cmpStrHard);\n\nmy %a = my %b = ( \"this\" => \"that\", \"extra\" => [ \"more\", \"stuff\" ] );\n$a{EXTRA} = \\%b;\n$b{EXTRA} = \\%a;\n\nprintf \"a and b contain %s hashes\\n\",\ncmpStr(\\%a, \\%b) == 0 ? \"the same\" : \"different\";\n\nprintf \"a and b contain %s hashes\\n\",\ncmpStrHard(\\%a, \\%b) == 0 ? \"the same\" : \"different\";\n\nThe first reports that both those the hashes contain the same data,\nwhile the second reports that they do not. Which you prefer is left as\nan exercise to the reader.\n\nHow do I find the first array element for which a condition is true?\nTo find the first array element which satisfies a condition, you can use\nthe first() function in the List::Util module, which comes with Perl\n5.8. This example finds the first element that contains \"Perl\".\n\nuse List::Util qw(first);\n\nmy $element = first { /Perl/ } @array;\n\nIf you cannot use List::Util, you can make your own loop to do the same\nthing. Once you find the element, you stop the loop with last.\n\nmy $found;\nforeach ( @array ) {\nif( /Perl/ ) { $found = $; last }\n}\n\nIf you want the array index, use the firstidx() function from\n\"List::MoreUtils\":\n\nuse List::MoreUtils qw(firstidx);\nmy $index = firstidx { /Perl/ } @array;\n\nOr write it yourself, iterating through the indices and checking the\narray element at each index until you find one that satisfies the\ncondition:\n\nmy( $found, $index ) = ( undef, -1 );\nfor( $i = 0; $i < @array; $i++ ) {\nif( $array[$i] =~ /Perl/ ) {\n$found = $array[$i];\n$index = $i;\nlast;\n}\n}\n\nHow do I handle linked lists?\n(contributed by brian d foy)\n\nPerl's arrays do not have a fixed size, so you don't need linked lists\nif you just want to add or remove items. You can use array operations\nsuch as \"push\", \"pop\", \"shift\", \"unshift\", or \"splice\" to do that.\n\nSometimes, however, linked lists can be useful in situations where you\nwant to \"shard\" an array so you have many small arrays instead of a\nsingle big array. You can keep arrays longer than Perl's largest array\nindex, lock smaller arrays separately in threaded programs, reallocate\nless memory, or quickly insert elements in the middle of the chain.\n\nSteve Lembark goes through the details in his YAPC::NA 2009 talk \"Perly\nLinked Lists\" ( <http://www.slideshare.net/lembark/perly-linked-lists>\n), although you can just use his LinkedList::Single module.\n\nHow do I handle circular lists?\n(contributed by brian d foy)\n\nIf you want to cycle through an array endlessly, you can increment the\nindex modulo the number of elements in the array:\n\nmy @array = qw( a b c );\nmy $i = 0;\n\nwhile( 1 ) {\nprint $array[ $i++ % @array ], \"\\n\";\nlast if $i > 20;\n}\n\nYou can also use Tie::Cycle to use a scalar that always has the next\nelement of the circular array:\n\nuse Tie::Cycle;\n\ntie my $cycle, 'Tie::Cycle', [ qw( FFFFFF 000000 FFFF00 ) ];\n\nprint $cycle; # FFFFFF\nprint $cycle; # 000000\nprint $cycle; # FFFF00\n\nThe Array::Iterator::Circular creates an iterator object for circular\narrays:\n\nuse Array::Iterator::Circular;\n\nmy $coloriterator = Array::Iterator::Circular->new(\nqw(red green blue orange)\n);\n\nforeach ( 1 .. 20 ) {\nprint $coloriterator->next, \"\\n\";\n}\n\nHow do I shuffle an array randomly?\nIf you either have Perl 5.8.0 or later installed, or if you have\nScalar-List-Utils 1.03 or later installed, you can say:\n\nuse List::Util 'shuffle';\n\n@shuffled = shuffle(@list);\n\nIf not, you can use a Fisher-Yates shuffle.\n\nsub fisheryatesshuffle {\nmy $deck = shift;  # $deck is a reference to an array\nreturn unless @$deck; # must not be empty!\n\nmy $i = @$deck;\nwhile (--$i) {\nmy $j = int rand ($i+1);\n@$deck[$i,$j] = @$deck[$j,$i];\n}\n}\n\n# shuffle my mpeg collection\n#\nmy @mpeg = <audio/*/*.mp3>;\nfisheryatesshuffle( \\@mpeg );    # randomize @mpeg in place\nprint @mpeg;\n\nNote that the above implementation shuffles an array in place, unlike\nthe List::Util::shuffle() which takes a list and returns a new shuffled\nlist.\n\nYou've probably seen shuffling algorithms that work using splice,\nrandomly picking another element to swap the current element with\n\nsrand;\n@new = ();\n@old = 1 .. 10;  # just a demo\nwhile (@old) {\npush(@new, splice(@old, rand @old, 1));\n}\n\nThis is bad because splice is already O(N), and since you do it N times,\nyou just invented a quadratic algorithm; that is, O(N2). This does not\nscale, although Perl is so efficient that you probably won't notice this\nuntil you have rather largish arrays.\n\nHow do I process/modify each element of an array?\nUse \"for\"/\"foreach\":\n\nfor (@lines) {\ns/foo/bar/;    # change that word\ntr/XZ/ZX/;    # swap those letters\n}\n\nHere's another; let's compute spherical volumes:\n\nmy @volumes = @radii;\nfor (@volumes) {   # @volumes has changed parts\n$ = 3;\n$ *= (4/3) * 3.14159;  # this will be constant folded\n}\n\nwhich can also be done with map() which is made to transform one list\ninto another:\n\nmy @volumes = map {$  3 * (4/3) * 3.14159} @radii;\n\nIf you want to do the same thing to modify the values of the hash, you\ncan use the \"values\" function. As of Perl 5.6 the values are not copied,\nso if you modify $orbit (in this case), you modify the value.\n\nfor my $orbit ( values %orbits ) {\n($orbit = 3) *= (4/3) * 3.14159;\n}\n\nPrior to perl 5.6 \"values\" returned copies of the values, so older perl\ncode often contains constructions such as @orbits{keys %orbits} instead\nof \"values %orbits\" where the hash is to be modified.\n\nHow do I select a random element from an array?\nUse the rand() function (see \"rand\" in perlfunc):\n\nmy $index   = rand @array;\nmy $element = $array[$index];\n\nOr, simply:\n\nmy $element = $array[ rand @array ];\n\nHow do I permute N elements of a list?\nUse the List::Permutor module on CPAN. If the list is actually an array,\ntry the Algorithm::Permute module (also on CPAN). It's written in XS\ncode and is very efficient:\n\nuse Algorithm::Permute;\n\nmy @array = 'a'..'d';\nmy $piterator = Algorithm::Permute->new ( \\@array );\n\nwhile (my @perm = $piterator->next) {\nprint \"next permutation: (@perm)\\n\";\n}\n\nFor even faster execution, you could do:\n\nuse Algorithm::Permute;\n\nmy @array = 'a'..'d';\n\nAlgorithm::Permute::permute {\nprint \"next permutation: (@array)\\n\";\n} @array;\n\nHere's a little program that generates all permutations of all the words\non each line of input. The algorithm embodied in the permute() function\nis discussed in Volume 4 (still unpublished) of Knuth's *The Art of\nComputer Programming* and will work on any list:\n\n#!/usr/bin/perl -n\n# Fischer-Krause ordered permutation generator\n\nsub permute (&@) {\nmy $code = shift;\nmy @idx = 0..$#;\nwhile ( $code->(@[@idx]) ) {\nmy $p = $#idx;\n--$p while $idx[$p-1] > $idx[$p];\nmy $q = $p or return;\npush @idx, reverse splice @idx, $p;\n++$q while $idx[$p-1] > $idx[$q];\n@idx[$p-1,$q]=@idx[$q,$p-1];\n}\n}\n\npermute { print \"@\\n\" } split;\n\nThe Algorithm::Loops module also provides the \"NextPermute\" and\n\"NextPermuteNum\" functions which efficiently find all unique\npermutations of an array, even if it contains duplicate values,\nmodifying it in-place: if its elements are in reverse-sorted order then\nthe array is reversed, making it sorted, and it returns false; otherwise\nthe next permutation is returned.\n\n\"NextPermute\" uses string order and \"NextPermuteNum\" numeric order, so\nyou can enumerate all the permutations of 0..9 like this:\n\nuse Algorithm::Loops qw(NextPermuteNum);\n\nmy @list= 0..9;\ndo { print \"@list\\n\" } while NextPermuteNum @list;\n\nHow do I manipulate arrays of bits?\nUse pack() and unpack(), or else vec() and the bitwise operations.\n\nFor example, you don't have to store individual bits in an array (which\nwould mean that you're wasting a lot of space). To convert an array of\nbits to a string, use vec() to set the right bits. This sets $vec to\nhave bit N set only if $ints[N] was set:\n\nmy @ints = (...); # array of bits, e.g. ( 1, 0, 0, 1, 1, 0 ... )\nmy $vec = '';\nforeach( 0 .. $#ints ) {\nvec($vec,$,1) = 1 if $ints[$];\n}\n\nThe string $vec only takes up as many bits as it needs. For instance, if\nyou had 16 entries in @ints, $vec only needs two bytes to store them\n(not counting the scalar variable overhead).\n\nHere's how, given a vector in $vec, you can get those bits into your\n@ints array:\n\nsub bitvectolist {\nmy $vec = shift;\nmy @ints;\n# Find null-byte density then select best algorithm\nif ($vec =~ tr/\\0// / length $vec > 0.95) {\nuse integer;\nmy $i;\n\n# This method is faster with mostly null-bytes\nwhile($vec =~ /[^\\0]/g ) {\n$i = -9 + 8 * pos $vec;\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\n}\n}\nelse {\n# This method is a fast general algorithm\nuse integer;\nmy $bits = unpack \"b*\", $vec;\npush @ints, 0 if $bits =~ s/^(\\d)// && $1;\npush @ints, pos $bits while($bits =~ /1/g);\n}\n\nreturn \\@ints;\n}\n\nThis method gets faster the more sparse the bit vector is. (Courtesy of\nTim Bunce and Winfried Koenig.)\n\nYou can make the while loop a lot shorter with this suggestion from\nBenjamin Goldberg:\n\nwhile($vec =~ /[^\\0]+/g ) {\npush @ints, grep vec($vec, $, 1), $-[0] * 8 .. $+[0] * 8;\n}\n\nOr use the CPAN module Bit::Vector:\n\nmy $vector = Bit::Vector->new($numofbits);\n$vector->IndexListStore(@ints);\nmy @ints = $vector->IndexListRead();\n\nBit::Vector provides efficient methods for bit vector, sets of small\nintegers and \"big int\" math.\n\nHere's a more extensive illustration using vec():\n\n# vec demo\nmy $vector = \"\\xff\\x0f\\xef\\xfe\";\nprint \"Ilya's string \\\\xff\\\\x0f\\\\xef\\\\xfe represents the number \",\nunpack(\"N\", $vector), \"\\n\";\nmy $isset = vec($vector, 23, 1);\nprint \"Its 23rd bit is \", $isset ? \"set\" : \"clear\", \".\\n\";\npvec($vector);\n\nsetvec(1,1,1);\nsetvec(3,1,1);\nsetvec(23,1,1);\n\nsetvec(3,1,3);\nsetvec(3,2,3);\nsetvec(3,4,3);\nsetvec(3,4,7);\nsetvec(3,8,3);\nsetvec(3,8,7);\n\nsetvec(0,32,17);\nsetvec(1,32,17);\n\nsub setvec {\nmy ($offset, $width, $value) = @;\nmy $vector = '';\nvec($vector, $offset, $width) = $value;\nprint \"offset=$offset width=$width value=$value\\n\";\npvec($vector);\n}\n\nsub pvec {\nmy $vector = shift;\nmy $bits = unpack(\"b*\", $vector);\nmy $i = 0;\nmy $BASE = 8;\n\nprint \"vector length in bytes: \", length($vector), \"\\n\";\n@bytes = unpack(\"A8\" x length($vector), $bits);\nprint \"bits are: @bytes\\n\\n\";\n}\n\nWhat happens if I add or remove keys from a hash while iterating over it?\n(contributed by brian d foy)\n\nThe easy answer is \"Don't do that!\"\n\nIf you iterate through the hash with each(), you can delete the key most\nrecently returned without worrying about it. If you delete or add other\nkeys, the iterator may skip or double up on them since perl may\nrearrange the hash table. See the entry for each() in perlfunc.\n\nHow do I look up a hash element by value?\nCreate a reverse hash:\n\nmy %byvalue = reverse %bykey;\nmy $key = $byvalue{$value};\n\nThat's not particularly efficient. It would be more space-efficient to\nuse:\n\nwhile (my ($key, $value) = each %bykey) {\n$byvalue{$value} = $key;\n}\n\nIf your hash could have repeated values, the methods above will only\nfind one of the associated keys. This may or may not worry you. If it\ndoes worry you, you can always reverse the hash into a hash of arrays\ninstead:\n\nwhile (my ($key, $value) = each %bykey) {\npush @{$keylistbyvalue{$value}}, $key;\n}\n\nHow do I sort a hash (optionally by value instead of key)?\n(contributed by brian d foy)\n\nTo sort a hash, start with the keys. In this example, we give the list\nof keys to the sort function which then compares them ASCIIbetically\n(which might be affected by your locale settings). The output list has\nthe keys in ASCIIbetical order. Once we have the keys, we can go through\nthem to create a report which lists the keys in ASCIIbetical order.\n\nmy @keys = sort { $a cmp $b } keys %hash;\n\nforeach my $key ( @keys ) {\nprintf \"%-20s %6d\\n\", $key, $hash{$key};\n}\n\nWe could get more fancy in the sort() block though. Instead of comparing\nthe keys, we can compute a value with them and use that value as the\ncomparison.\n\nFor instance, to make our report order case-insensitive, we use \"lc\" to\nlowercase the keys before comparing them:\n\nmy @keys = sort { lc $a cmp lc $b } keys %hash;\n\nNote: if the computation is expensive or the hash has many elements, you\nmay want to look at the Schwartzian Transform to cache the computation\nresults.\n\nIf we want to sort by the hash value instead, we use the hash key to\nlook it up. We still get out a list of keys, but this time they are\nordered by their value.\n\nmy @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;\n\nFrom there we can get more complex. If the hash values are the same, we\ncan provide a secondary sort on the hash key.\n\nmy @keys = sort {\n$hash{$a} <=> $hash{$b}\nor\n\"\\L$a\" cmp \"\\L$b\"\n} keys %hash;\n\nHow can I always keep my hash sorted?\nYou can look into using the \"DBFile\" module and tie() using the\n$DBBTREE hash bindings as documented in \"In Memory Databases\" in\nDBFile. The Tie::IxHash module from CPAN might also be instructive.\nAlthough this does keep your hash sorted, you might not like the\nslowdown you suffer from the tie interface. Are you sure you need to do\nthis? :)\n\nWhat's the difference between \"delete\" and \"undef\" with hashes?\nHashes contain pairs of scalars: the first is the key, the second is the\nvalue. The key will be coerced to a string, although the value can be\nany kind of scalar: string, number, or reference. If a key $key is\npresent in %hash, exists($hash{$key}) will return true. The value for a\ngiven key can be \"undef\", in which case $hash{$key} will be \"undef\"\nwhile \"exists $hash{$key}\" will return true. This corresponds to ($key,\n\"undef\") being in the hash.\n\nPictures help... Here's the %hash table:\n\nkeys  values\n+------+------+\n|  a   |  3   |\n|  x   |  7   |\n|  d   |  0   |\n|  e   |  2   |\n+------+------+\n\nAnd these conditions hold\n\n$hash{'a'}                       is true\n$hash{'d'}                       is false\ndefined $hash{'d'}               is true\ndefined $hash{'a'}               is true\nexists $hash{'a'}                is true (Perl 5 only)\ngrep ($ eq 'a', keys %hash)     is true\n\nIf you now say\n\nundef $hash{'a'}\n\nyour table now reads:\n\nkeys  values\n+------+------+\n|  a   | undef|\n|  x   |  7   |\n|  d   |  0   |\n|  e   |  2   |\n+------+------+\n\nand these conditions now hold; changes in caps:\n\n$hash{'a'}                       is FALSE\n$hash{'d'}                       is false\ndefined $hash{'d'}               is true\ndefined $hash{'a'}               is FALSE\nexists $hash{'a'}                is true (Perl 5 only)\ngrep ($ eq 'a', keys %hash)     is true\n\nNotice the last two: you have an undef value, but a defined key!\n\nNow, consider this:\n\ndelete $hash{'a'}\n\nyour table now reads:\n\nkeys  values\n+------+------+\n|  x   |  7   |\n|  d   |  0   |\n|  e   |  2   |\n+------+------+\n\nand these conditions now hold; changes in caps:\n\n$hash{'a'}                       is false\n$hash{'d'}                       is false\ndefined $hash{'d'}               is true\ndefined $hash{'a'}               is false\nexists $hash{'a'}                is FALSE (Perl 5 only)\ngrep ($ eq 'a', keys %hash)     is FALSE\n\nSee, the whole entry is gone!\n\nHow can I store a multidimensional array in a DBM file?\nEither stringify the structure yourself (no fun), or else get the MLDBM\n(which uses Data::Dumper) module from CPAN and layer it on top of either\nDBFile or GDBMFile. You might also try DBM::Deep, but it can be a bit\nslow.\n\nHow can I make my hash remember the order I put elements into it?\nUse the Tie::IxHash from CPAN.\n\nuse Tie::IxHash;\n\ntie my %myhash, 'Tie::IxHash';\n\nfor (my $i=0; $i<20; $i++) {\n$myhash{$i} = 2*$i;\n}\n\nmy @keys = keys %myhash;\n# @keys = (0,1,2,3,...)\n\nWhy does passing a subroutine an undefined element in a hash create it?\n(contributed by brian d foy)\n\nAre you using a really old version of Perl?\n\nNormally, accessing a hash key's value for a nonexistent key will *not*\ncreate the key.\n\nmy %hash  = ();\nmy $value = $hash{ 'foo' };\nprint \"This won't print\\n\" if exists $hash{ 'foo' };\n\nPassing $hash{ 'foo' } to a subroutine used to be a special case,\nthough. Since you could assign directly to $[0], Perl had to be ready\nto make that assignment so it created the hash key ahead of time:\n\nmysub( $hash{ 'foo' } );\nprint \"This will print before 5.004\\n\" if exists $hash{ 'foo' };\n\nsub mysub {\n# $[0] = 'bar'; # create hash key in case you do this\n1;\n}\n\nSince Perl 5.004, however, this situation is a special case and Perl\ncreates the hash key only when you make the assignment:\n\nmysub( $hash{ 'foo' } );\nprint \"This will print, even after 5.004\\n\" if exists $hash{ 'foo' };\n\nsub mysub {\n$[0] = 'bar';\n}\n\nHowever, if you want the old behavior (and think carefully about that\nbecause it's a weird side effect), you can pass a hash slice instead.\nPerl 5.004 didn't make this a special case:\n\nmysub( @hash{ qw/foo/ } );\n\nHow can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?\nUsually a hash ref, perhaps like this:\n\n$record = {\nNAME   => \"Jason\",\nEMPNO  => 132,\nTITLE  => \"deputy peon\",\nAGE    => 23,\nSALARY => 37000,\nPALS   => [ \"Norbert\", \"Rhys\", \"Phineas\"],\n};\n\nReferences are documented in perlref and perlreftut. Examples of complex\ndata structures are given in perldsc and perllol. Examples of structures\nand object-oriented classes are in perlootut.\n\nHow can I check if a key exists in a multilevel hash?\n(contributed by brian d foy)\n\nThe trick to this problem is avoiding accidental autovivification. If\nyou want to check three keys deep, you might naïvely try this:\n\nmy %hash;\nif( exists $hash{key1}{key2}{key3} ) {\n...;\n}\n\nEven though you started with a completely empty hash, after that call to\n\"exists\" you've created the structure you needed to check for \"key3\":\n\n%hash = (\n'key1' => {\n'key2' => {}\n}\n);\n\nThat's autovivification. You can get around this in a few ways. The\neasiest way is to just turn it off. The lexical \"autovivification\"\npragma is available on CPAN. Now you don't add to the hash:\n\n{\nno autovivification;\nmy %hash;\nif( exists $hash{key1}{key2}{key3} ) {\n...;\n}\n}\n\nThe Data::Diver module on CPAN can do it for you too. Its \"Dive\"\nsubroutine can tell you not only if the keys exist but also get the\nvalue:\n\nuse Data::Diver qw(Dive);\n\nmy @exists = Dive( \\%hash, qw(key1 key2 key3) );\nif(  ! @exists  ) {\n...; # keys do not exist\n}\nelsif(  ! defined $exists[0]  ) {\n...; # keys exist but value is undef\n}\n\nYou can easily do this yourself too by checking each level of the hash\nbefore you move onto the next level. This is essentially what\nData::Diver does for you:\n\nif( checkhash( \\%hash, qw(key1 key2 key3) ) ) {\n...;\n}\n\nsub checkhash {\nmy( $hash, @keys ) = @;\n\nreturn unless @keys;\n\nforeach my $key ( @keys ) {\nreturn unless eval { exists $hash->{$key} };\n$hash = $hash->{$key};\n}\n\nreturn 1;\n}\n\nHow do I handle binary data correctly?\nPerl is binary-clean, so it can handle binary data just fine. On Windows\nor DOS, however, you have to use \"binmode\" for binary files to avoid\nconversions for line endings. In general, you should use \"binmode\" any\ntime you want to work with binary data.\n\nAlso see \"binmode\" in perlfunc or perlopentut.\n\nIf you're concerned about 8-bit textual data then see perllocale. If you\nwant to deal with multibyte characters, however, there are some gotchas.\nSee the section on Regular Expressions.\n\nHow do I determine whether a scalar is a number/whole/integer/float?\nAssuming that you don't care about IEEE notations like \"NaN\" or\n\"Infinity\", you probably just want to use a regular expression (see also\nperlretut and perlre):\n\nuse 5.010;\n\nif ( /\\D/ )\n{ say \"\\thas nondigits\"; }\nif ( /^\\d+\\z/ )\n{ say \"\\tis a whole number\"; }\nif ( /^-?\\d+\\z/ )\n{ say \"\\tis an integer\"; }\nif ( /^[+-]?\\d+\\z/ )\n{ say \"\\tis a +/- integer\"; }\nif ( /^-?(?:\\d+\\.?|\\.\\d)\\d*\\z/ )\n{ say \"\\tis a real number\"; }\nif ( /^[+-]?(?=\\.?\\d)\\d*\\.?\\d*(?:e[+-]?\\d+)?\\z/i )\n{ say \"\\tis a C float\" }\n\nThere are also some commonly used modules for the task. Scalar::Util\n(distributed with 5.8) provides access to perl's internal function\n\"lookslikenumber\" for determining whether a variable looks like a\nnumber. Data::Types exports functions that validate data types using\nboth the above and other regular expressions. Thirdly, there is\nRegexp::Common which has regular expressions to match various types of\nnumbers. Those three modules are available from the CPAN.\n\nIf you're on a POSIX system, Perl supports the \"POSIX::strtod\" function\nfor converting strings to doubles (and also \"POSIX::strtol\" for longs).\nIts semantics are somewhat cumbersome, so here's a \"getnum\" wrapper\nfunction for more convenient access. This function takes a string and\nreturns the number it found, or \"undef\" for input that isn't a C float.\nThe \"isnumeric\" function is a front end to \"getnum\" if you just want to\nsay, \"Is this a float?\"\n\nsub getnum {\nuse POSIX qw(strtod);\nmy $str = shift;\n$str =~ s/^\\s+//;\n$str =~ s/\\s+$//;\n$! = 0;\nmy($num, $unparsed) = strtod($str);\nif (($str eq '') || ($unparsed != 0) || $!) {\nreturn undef;\n}\nelse {\nreturn $num;\n}\n}\n\nsub isnumeric { defined getnum($[0]) }\n\nOr you could check out the String::Scanf module on the CPAN instead.\n\nHow do I keep persistent data across program calls?\nFor some specific applications, you can use one of the DBM modules. See\nAnyDBMFile. More generically, you should consult the FreezeThaw or\nStorable modules from CPAN. Starting from Perl 5.8, Storable is part of\nthe standard distribution. Here's one example using Storable's \"store\"\nand \"retrieve\" functions:\n\nuse Storable;\nstore(\\%hash, \"filename\");\n\n# later on...\n$href = retrieve(\"filename\");        # by ref\n%hash = %{ retrieve(\"filename\") };   # direct to hash\n\nHow do I define methods for every class/object?\n(contributed by Ben Morrow)\n\nYou can use the \"UNIVERSAL\" class (see UNIVERSAL). However, please be\nvery careful to consider the consequences of doing this: adding methods\nto every object is very likely to have unintended consequences. If\npossible, it would be better to have all your object inherit from some\ncommon base class, or to use an object system like Moose that supports\nroles.\n\nHow do I pack arrays of doubles or floats for XS code?\nThe arrays.h/arrays.c code in the PGPLOT module on CPAN does just this.\nIf you're doing a lot of float or double processing, consider using the\nPDL module from CPAN instead--it makes number-crunching easy.\n\nSee <https://metacpan.org/release/PGPLOT> for the code.\n"
                }
            ]
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq5.pod": {
            "content": "How do I flush/unbuffer an output filehandle? Why must I do this?\n(contributed by brian d foy)\n\nYou might like to read Mark Jason Dominus's \"Suffering From Buffering\"\nat <http://perl.plover.com/FAQs/Buffering.html> .\n\nPerl normally buffers output so it doesn't make a system call for every\nbit of output. By saving up output, it makes fewer expensive system\ncalls. For instance, in this little bit of code, you want to print a dot\nto the screen for every line you process to watch the progress of your\nprogram. Instead of seeing a dot for every line, Perl buffers the output\nand you have a long wait before you see a row of 50 dots all at once:\n\n# long wait, then row of dots all at once\nwhile( <> ) {\nprint \".\";\nprint \"\\n\" unless ++$count % 50;\n\n#... expensive line processing operations\n}\n\nTo get around this, you have to unbuffer the output filehandle, in this\ncase, \"STDOUT\". You can set the special variable $| to a true value\n(mnemonic: making your filehandles \"piping hot\"):\n\n$|++;\n\n# dot shown immediately\nwhile( <> ) {\nprint \".\";\nprint \"\\n\" unless ++$count % 50;\n\n#... expensive line processing operations\n}\n\nThe $| is one of the per-filehandle special variables, so each\nfilehandle has its own copy of its value. If you want to merge standard\noutput and standard error for instance, you have to unbuffer each\n(although STDERR might be unbuffered by default):\n\n{\nmy $previousdefault = select(STDOUT);  # save previous default\n$|++;                                   # autoflush STDOUT\nselect(STDERR);\n$|++;                                   # autoflush STDERR, to be sure\nselect($previousdefault);              # restore previous default\n}\n\n# now should alternate . and +\nwhile( 1 ) {\nsleep 1;\nprint STDOUT \".\";\nprint STDERR \"+\";\nprint STDOUT \"\\n\" unless ++$count % 25;\n}\n\nBesides the $| special variable, you can use \"binmode\" to give your\nfilehandle a \":unix\" layer, which is unbuffered:\n\nbinmode( STDOUT, \":unix\" );\n\nwhile( 1 ) {\nsleep 1;\nprint \".\";\nprint \"\\n\" unless ++$count % 50;\n}\n\nFor more information on output layers, see the entries for \"binmode\" and\nopen in perlfunc, and the PerlIO module documentation.\n\nIf you are using IO::Handle or one of its subclasses, you can call the\n\"autoflush\" method to change the settings of the filehandle:\n\nuse IO::Handle;\nopen my( $iofh ), \">\", \"output.txt\";\n$iofh->autoflush(1);\n\nThe IO::Handle objects also have a \"flush\" method. You can flush the\nbuffer any time you want without auto-buffering\n\n$iofh->flush;\n\nHow do I change, delete, or insert a line in a file, or append to the beginning of a file?\n(contributed by brian d foy)\n\nThe basic idea of inserting, changing, or deleting a line from a text\nfile involves reading and printing the file to the point you want to\nmake the change, making the change, then reading and printing the rest\nof the file. Perl doesn't provide random access to lines (especially\nsince the record input separator, $/, is mutable), although modules such\nas Tie::File can fake it.\n\nA Perl program to do these tasks takes the basic form of opening a file,\nprinting its lines, then closing the file:\n\nopen my $in,  '<',  $file      or die \"Can't read old file: $!\";\nopen my $out, '>', \"$file.new\" or die \"Can't write new file: $!\";\n\nwhile( <$in> ) {\nprint $out $;\n}\n\nclose $out;\n\nWithin that basic form, add the parts that you need to insert, change,\nor delete lines.\n\nTo prepend lines to the beginning, print those lines before you enter\nthe loop that prints the existing lines.\n\nopen my $in,  '<',  $file      or die \"Can't read old file: $!\";\nopen my $out, '>', \"$file.new\" or die \"Can't write new file: $!\";\n\nprint $out \"# Add this line to the top\\n\"; # <--- HERE'S THE MAGIC\n\nwhile( <$in> ) {\nprint $out $;\n}\n\nclose $out;\n\nTo change existing lines, insert the code to modify the lines inside the\n\"while\" loop. In this case, the code finds all lowercased versions of\n\"perl\" and uppercases them. The happens for every line, so be sure that\nyou're supposed to do that on every line!\n\nopen my $in,  '<',  $file      or die \"Can't read old file: $!\";\nopen my $out, '>', \"$file.new\" or die \"Can't write new file: $!\";\n\nprint $out \"# Add this line to the top\\n\";\n\nwhile( <$in> ) {\ns/\\b(perl)\\b/Perl/g;\nprint $out $;\n}\n\nclose $out;\n\nTo change only a particular line, the input line number, $., is useful.\nFirst read and print the lines up to the one you want to change. Next,\nread the single line you want to change, change it, and print it. After\nthat, read the rest of the lines and print those:\n\nwhile( <$in> ) { # print the lines before the change\nprint $out $;\nlast if $. == 4; # line number before change\n}\n\nmy $line = <$in>;\n$line =~ s/\\b(perl)\\b/Perl/g;\nprint $out $line;\n\nwhile( <$in> ) { # print the rest of the lines\nprint $out $;\n}\n\nTo skip lines, use the looping controls. The \"next\" in this example\nskips comment lines, and the \"last\" stops all processing once it\nencounters either \"END\" or \"DATA\".\n\nwhile( <$in> ) {\nnext if /^\\s+#/;             # skip comment lines\nlast if /^(END|DATA)$/;  # stop at end of code marker\nprint $out $;\n}\n\nDo the same sort of thing to delete a particular line by using \"next\" to\nskip the lines you don't want to show up in the output. This example\nskips every fifth line:\n\nwhile( <$in> ) {\nnext unless $. % 5;\nprint $out $;\n}\n\nIf, for some odd reason, you really want to see the whole file at once\nrather than processing line-by-line, you can slurp it in (as long as you\ncan fit the whole thing in memory!):\n\nopen my $in,  '<',  $file      or die \"Can't read old file: $!\"\nopen my $out, '>', \"$file.new\" or die \"Can't write new file: $!\";\n\nmy $content = do { local $/; <$in> }; # slurp!\n\n# do your magic here\n\nprint $out $content;\n\nModules such as Path::Tiny and Tie::File can help with that too. If you\ncan, however, avoid reading the entire file at once. Perl won't give\nthat memory back to the operating system until the process finishes.\n\nYou can also use Perl one-liners to modify a file in-place. The\nfollowing changes all 'Fred' to 'Barney' in inFile.txt, overwriting the\nfile with the new contents. With the \"-p\" switch, Perl wraps a \"while\"\nloop around the code you specify with \"-e\", and \"-i\" turns on in-place\nediting. The current line is in $. With \"-p\", Perl automatically prints\nthe value of $ at the end of the loop. See perlrun for more details.\n\nperl -pi -e 's/Fred/Barney/' inFile.txt\n\nTo make a backup of \"inFile.txt\", give \"-i\" a file extension to add:\n\nperl -pi.bak -e 's/Fred/Barney/' inFile.txt\n\nTo change only the fifth line, you can add a test checking $., the input\nline number, then only perform the operation when the test passes:\n\nperl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt\n\nTo add lines before a certain line, you can add a line (or lines!)\nbefore Perl prints $:\n\nperl -pi -e 'print \"Put before third line\\n\" if $. == 3' inFile.txt\n\nYou can even add a line to the beginning of a file, since the current\nline prints at the end of the loop:\n\nperl -pi -e 'print \"Put before first line\\n\" if $. == 1' inFile.txt\n\nTo insert a line after one already in the file, use the \"-n\" switch.\nIt's just like \"-p\" except that it doesn't print $ at the end of the\nloop, so you have to do that yourself. In this case, print $ first,\nthen print the line that you want to add.\n\nperl -ni -e 'print; print \"Put after fifth line\\n\" if $. == 5' inFile.txt\n\nTo delete lines, only print the ones that you want.\n\nperl -ni -e 'print if /d/' inFile.txt\n\nHow do I count the number of lines in a file?\n(contributed by brian d foy)\n\nConceptually, the easiest way to count the lines in a file is to simply\nread them and count them:\n\nmy $count = 0;\nwhile( <$fh> ) { $count++; }\n\nYou don't really have to count them yourself, though, since Perl already\ndoes that with the $. variable, which is the current line number from\nthe last filehandle read:\n\n1 while( <$fh> );\nmy $count = $.;\n\nIf you want to use $., you can reduce it to a simple one-liner, like one\nof these:\n\n% perl -lne '} print $.; {'    file\n\n% perl -lne 'END { print $. }' file\n\nThose can be rather inefficient though. If they aren't fast enough for\nyou, you might just read chunks of data and count the number of\nnewlines:\n\nmy $lines = 0;\nopen my($fh), '<:raw', $filename or die \"Can't open $filename: $!\";\nwhile( sysread $fh, $buffer, 4096 ) {\n$lines += ( $buffer =~ tr/\\n// );\n}\nclose $fh;\n\nHowever, that doesn't work if the line ending isn't a newline. You might\nchange that \"tr///\" to a \"s///\" so you can count the number of times the\ninput record separator, $/, shows up:\n\nmy $lines = 0;\nopen my($fh), '<:raw', $filename or die \"Can't open $filename: $!\";\nwhile( sysread $fh, $buffer, 4096 ) {\n$lines += ( $buffer =~ s|$/||g; );\n}\nclose $fh;\n\nIf you don't mind shelling out, the \"wc\" command is usually the fastest,\neven with the extra interprocess overhead. Ensure that you have an\nuntainted filename though:\n\n#!perl -T\n\n$ENV{PATH} = undef;\n\nmy $lines;\nif( $filename =~ /^([0-9a-z.]+)\\z/ ) {\n$lines = `/usr/bin/wc -l $1`\nchomp $lines;\n}\n\nHow do I delete the last N lines from a file?\n(contributed by brian d foy)\n\nThe easiest conceptual solution is to count the lines in the file then\nstart at the beginning and print the number of lines (minus the last N)\nto a new file.\n\nMost often, the real question is how you can delete the last N lines\nwithout making more than one pass over the file, or how to do it without\na lot of copying. The easy concept is the hard reality when you might\nhave millions of lines in your file.\n\nOne trick is to use File::ReadBackwards, which starts at the end of the\nfile. That module provides an object that wraps the real filehandle to\nmake it easy for you to move around the file. Once you get to the spot\nyou need, you can get the actual filehandle and work with it as normal.\nIn this case, you get the file position at the end of the last line you\nwant to keep and truncate the file to that point:\n\nuse File::ReadBackwards;\n\nmy $filename = 'test.txt';\nmy $Linestotruncate = 2;\n\nmy $bw = File::ReadBackwards->new( $filename )\nor die \"Could not read backwards in [$filename]: $!\";\n\nmy $linesfromend = 0;\nuntil( $bw->eof or $linesfromend == $Linestotruncate ) {\nprint \"Got: \", $bw->readline;\n$linesfromend++;\n}\n\ntruncate( $filename, $bw->tell );\n\nThe File::ReadBackwards module also has the advantage of setting the\ninput record separator to a regular expression.\n\nYou can also use the Tie::File module which lets you access the lines\nthrough a tied array. You can use normal array operations to modify your\nfile, including setting the last index and using \"splice\".\n\nHow can I use Perl's \"-i\" option from within a program?\n\"-i\" sets the value of Perl's $^I variable, which in turn affects the\nbehavior of \"<>\"; see perlrun for more details. By modifying the\nappropriate variables directly, you can get the same behavior within a\nlarger program. For example:\n\n# ...\n{\nlocal($^I, @ARGV) = ('.orig', glob(\"*.c\"));\nwhile (<>) {\nif ($. == 1) {\nprint \"This line should appear at the top of each file\\n\";\n}\ns/\\b(p)earl\\b/${1}erl/i;        # Correct typos, preserving case\nprint;\nclose ARGV if eof;              # Reset $.\n}\n}\n# $^I and @ARGV return to their old values here\n\nThis block modifies all the \".c\" files in the current directory, leaving\na backup of the original data from each file in a new \".c.orig\" file.\n\nHow can I copy a file?\n(contributed by brian d foy)\n\nUse the File::Copy module. It comes with Perl and can do a true copy\nacross file systems, and it does its magic in a portable fashion.\n\nuse File::Copy;\n\ncopy( $original, $newcopy ) or die \"Copy failed: $!\";\n\nIf you can't use File::Copy, you'll have to do the work yourself: open\nthe original file, open the destination file, then print to the\ndestination file as you read the original. You also have to remember to\ncopy the permissions, owner, and group to the new file.\n\nHow do I make a temporary file name?\nIf you don't need to know the name of the file, you can use open() with\n\"undef\" in place of the file name. In Perl 5.8 or later, the open()\nfunction creates an anonymous temporary file:\n\nopen my $tmp, '+>', undef or die $!;\n\nOtherwise, you can use the File::Temp module.\n\nuse File::Temp qw/ tempfile tempdir /;\n\nmy $dir = tempdir( CLEANUP => 1 );\n($fh, $filename) = tempfile( DIR => $dir );\n\n# or if you don't need to know the filename\n\nmy $fh = tempfile( DIR => $dir );\n\nThe File::Temp has been a standard module since Perl 5.6.1. If you don't\nhave a modern enough Perl installed, use the \"newtmpfile\" class method\nfrom the IO::File module to get a filehandle opened for reading and\nwriting. Use it if you don't need to know the file's name:\n\nuse IO::File;\nmy $fh = IO::File->newtmpfile()\nor die \"Unable to make new temporary file: $!\";\n\nIf you're committed to creating a temporary file by hand, use the\nprocess ID and/or the current time-value. If you need to have many\ntemporary files in one process, use a counter:\n\nBEGIN {\nuse Fcntl;\nuse File::Spec;\nmy $tempdir  = File::Spec->tmpdir();\nmy $filebase = sprintf \"%d-%d-0000\", $$, time;\nmy $basename = File::Spec->catfile($tempdir, $filebase);\n\nsub tempfile {\nmy $fh;\nmy $count = 0;\nuntil( defined(fileno($fh)) || $count++ > 100 ) {\n$basename =~ s/-(\\d+)$/\"-\" . (1 + $1)/e;\n# OEXCL is required for security reasons.\nsysopen $fh, $basename, OWRONLY|OEXCL|OCREAT;\n}\n\nif( defined fileno($fh) ) {\nreturn ($fh, $basename);\n}\nelse {\nreturn ();\n}\n}\n}\n\nHow can I manipulate fixed-record-length files?\nThe most efficient way is using pack() and unpack(). This is faster than\nusing substr() when taking many, many strings. It is slower for just a\nfew.\n\nHere is a sample chunk of code to break up and put back together again\nsome fixed-format input lines, in this case from the output of a normal,\nBerkeley-style ps:\n\n# sample input line:\n#   15158 p5  T      0:00 perl /home/tchrist/scripts/now-what\nmy $PST = 'A6 A4 A7 A5 A*';\nopen my $ps, '-|', 'ps';\nprint scalar <$ps>;\nmy @fields = qw( pid tt stat time command );\nwhile (<$ps>) {\nmy %process;\n@process{@fields} = unpack($PST, $);\nfor my $field ( @fields ) {\nprint \"$field: <$process{$field}>\\n\";\n}\nprint 'line=', pack($PST, @process{@fields} ), \"\\n\";\n}\n\nWe've used a hash slice in order to easily handle the fields of each\nrow. Storing the keys in an array makes it easy to operate on them as a\ngroup or loop over them with \"for\". It also avoids polluting the program\nwith global variables and using symbolic references.\n\nHow can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles?\nAs of perl5.6, open() autovivifies file and directory handles as\nreferences if you pass it an uninitialized scalar variable. You can then\npass these references just like any other scalar, and use them in the\nplace of named handles.\n\nopen my    $fh, $filename;\n\nopen local $fh, $filename;\n\nprint $fh \"Hello World!\\n\";\n\nprocessfile( $fh );\n\nIf you like, you can store these filehandles in an array or a hash. If\nyou access them directly, they aren't simple scalars and you need to\ngive \"print\" a little help by placing the filehandle reference in\nbraces. Perl can only figure it out on its own when the filehandle\nreference is a simple scalar.\n\nmy @fhs = ( $fh1, $fh2, $fh3 );\n\nfor( $i = 0; $i <= $#fhs; $i++ ) {\nprint {$fhs[$i]} \"just another Perl answer, \\n\";\n}\n\nBefore perl5.6, you had to deal with various typeglob idioms which you\nmay see in older code.\n\nopen FILE, \"> $filename\";\nprocesstypeglob(   *FILE );\nprocessreference( \\*FILE );\n\nsub processtypeglob  { local *FH = shift; print FH  \"Typeglob!\" }\nsub processreference { local $fh = shift; print $fh \"Reference!\" }\n\nIf you want to create many anonymous handles, you should check out the\nSymbol or IO::Handle modules.\n\nHow can I use a filehandle indirectly?\nAn indirect filehandle is the use of something other than a symbol in a\nplace that a filehandle is expected. Here are ways to get indirect\nfilehandles:\n\n$fh =   SOMEFH;       # bareword is strict-subs hostile\n$fh =  \"SOMEFH\";      # strict-refs hostile; same package only\n$fh =  *SOMEFH;       # typeglob\n$fh = \\*SOMEFH;       # ref to typeglob (bless-able)\n$fh =  *SOMEFH{IO};   # blessed IO::Handle from *SOMEFH typeglob\n\nOr, you can use the \"new\" method from one of the IO::* modules to create\nan anonymous filehandle and store that in a scalar variable.\n\nuse IO::Handle;                     # 5.004 or higher\nmy $fh = IO::Handle->new();\n\nThen use any of those as you would a normal filehandle. Anywhere that\nPerl is expecting a filehandle, an indirect filehandle may be used\ninstead. An indirect filehandle is just a scalar variable that contains\na filehandle. Functions like \"print\", \"open\", \"seek\", or the \"<FH>\"\ndiamond operator will accept either a named filehandle or a scalar\nvariable containing one:\n\n($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR);\nprint $ofh \"Type it: \";\nmy $got = <$ifh>\nprint $efh \"What was that: $got\";\n\nIf you're passing a filehandle to a function, you can write the function\nin two ways:\n\nsub acceptfh {\nmy $fh = shift;\nprint $fh \"Sending to indirect filehandle\\n\";\n}\n\nOr it can localize a typeglob and use the filehandle directly:\n\nsub acceptfh {\nlocal *FH = shift;\nprint  FH \"Sending to localized filehandle\\n\";\n}\n\nBoth styles work with either objects or typeglobs of real filehandles.\n(They might also work with strings under some circumstances, but this is\nrisky.)\n\nacceptfh(*STDOUT);\nacceptfh($handle);\n\nIn the examples above, we assigned the filehandle to a scalar variable\nbefore using it. That is because only simple scalar variables, not\nexpressions or subscripts of hashes or arrays, can be used with\nbuilt-ins like \"print\", \"printf\", or the diamond operator. Using\nsomething other than a simple scalar variable as a filehandle is illegal\nand won't even compile:\n\nmy @fd = (*STDIN, *STDOUT, *STDERR);\nprint $fd[1] \"Type it: \";                           # WRONG\nmy $got = <$fd[0]>                                  # WRONG\nprint $fd[2] \"What was that: $got\";                 # WRONG\n\nWith \"print\" and \"printf\", you get around this by using a block and an\nexpression where you would place the filehandle:\n\nprint  { $fd[1] } \"funny stuff\\n\";\nprintf { $fd[1] } \"Pity the poor %x.\\n\", 3735928559;\n# Pity the poor deadbeef.\n\nThat block is a proper block like any other, so you can put more\ncomplicated code there. This sends the message out to one of two places:\n\nmy $ok = -x \"/bin/cat\";\nprint { $ok ? $fd[1] : $fd[2] } \"cat stat $ok\\n\";\nprint { $fd[ 1+ ($ok || 0) ]  } \"cat stat $ok\\n\";\n\nThis approach of treating \"print\" and \"printf\" like object methods calls\ndoesn't work for the diamond operator. That's because it's a real\noperator, not just a function with a comma-less argument. Assuming\nyou've been storing typeglobs in your structure as we did above, you can\nuse the built-in function named \"readline\" to read a record just as \"<>\"\ndoes. Given the initialization shown above for @fd, this would work, but\nonly because readline() requires a typeglob. It doesn't work with\nobjects or strings, which might be a bug we haven't fixed yet.\n\n$got = readline($fd[0]);\n\nLet it be noted that the flakiness of indirect filehandles is not\nrelated to whether they're strings, typeglobs, objects, or anything\nelse. It's the syntax of the fundamental operators. Playing the object\ngame doesn't help you at all here.\n\nHow can I open a filehandle to a string?\n(contributed by Peter J. Holzer, hjp-usenet2@hjp.at)\n\nSince Perl 5.8.0 a file handle referring to a string can be created by\ncalling open with a reference to that string instead of the filename.\nThis file handle can then be used to read from or write to the string:\n\nopen(my $fh, '>', \\$string) or die \"Could not open string for writing\";\nprint $fh \"foo\\n\";\nprint $fh \"bar\\n\";    # $string now contains \"foo\\nbar\\n\"\n\nopen(my $fh, '<', \\$string) or die \"Could not open string for reading\";\nmy $x = <$fh>;    # $x now contains \"foo\\n\"\n\nWith older versions of Perl, the IO::String module provides similar\nfunctionality.\n\nHow can I translate tildes (~) in a filename?\nUse the <> (glob()) operator, documented in perlfunc. Versions of Perl\nolder than 5.6 require that you have a shell installed that groks\ntildes. Later versions of Perl have this feature built in. The\nFile::KGlob module (available from CPAN) gives more portable glob\nfunctionality.\n\nWithin Perl, you may use this directly:\n\n$filename =~ s{\n^ ~             # find a leading tilde\n(               # save this in $1\n[^/]        # a non-slash character\n*     # repeated 0 or more times (0 means me)\n)\n}{\n$1\n? (getpwnam($1))[7]\n: ( $ENV{HOME} || $ENV{LOGDIR} )\n}ex;\n\nHow come when I open a file read-write it wipes it out?\nBecause you're using something like this, which truncates the file\n*then* gives you read-write access:\n\nopen my $fh, '+>', '/path/name'; # WRONG (almost always)\n\nWhoops. You should instead use this, which will fail if the file doesn't\nexist:\n\nopen my $fh, '+<', '/path/name'; # open for update\n\nUsing \">\" always clobbers or creates. Using \"<\" never does either. The\n\"+\" doesn't change this.\n\nHere are examples of many kinds of file opens. Those using \"sysopen\" all\nassume that you've pulled in the constants from Fcntl:\n\nuse Fcntl;\n\nTo open file for reading:\n\nopen my $fh, '<', $path                               or die $!;\nsysopen my $fh, $path, ORDONLY                       or die $!;\n\nTo open file for writing, create new file if needed or else truncate old\nfile:\n\nopen my $fh, '>', $path                               or die $!;\nsysopen my $fh, $path, OWRONLY|OTRUNC|OCREAT       or die $!;\nsysopen my $fh, $path, OWRONLY|OTRUNC|OCREAT, 0666 or die $!;\n\nTo open file for writing, create new file, file must not exist:\n\nsysopen my $fh, $path, OWRONLY|OEXCL|OCREAT        or die $!;\nsysopen my $fh, $path, OWRONLY|OEXCL|OCREAT, 0666  or die $!;\n\nTo open file for appending, create if necessary:\n\nopen my $fh, '>>', $path                              or die $!;\nsysopen my $fh, $path, OWRONLY|OAPPEND|OCREAT      or die $!;\nsysopen my $fh, $path, OWRONLY|OAPPEND|OCREAT, 0666 or die $!;\n\nTo open file for appending, file must exist:\n\nsysopen my $fh, $path, OWRONLY|OAPPEND              or die $!;\n\nTo open file for update, file must exist:\n\nopen my $fh, '+<', $path                              or die $!;\nsysopen my $fh, $path, ORDWR                         or die $!;\n\nTo open file for update, create file if necessary:\n\nsysopen my $fh, $path, ORDWR|OCREAT                 or die $!;\nsysopen my $fh, $path, ORDWR|OCREAT, 0666           or die $!;\n\nTo open file for update, file must not exist:\n\nsysopen my $fh, $path, ORDWR|OEXCL|OCREAT          or die $!;\nsysopen my $fh, $path, ORDWR|OEXCL|OCREAT, 0666    or die $!;\n\nTo open a file without blocking, creating if necessary:\n\nsysopen my $fh, '/foo/somefile', OWRONLY|ONDELAY|OCREAT\nor die \"can't open /foo/somefile: $!\":\n\nBe warned that neither creation nor deletion of files is guaranteed to\nbe an atomic operation over NFS. That is, two processes might both\nsuccessfully create or unlink the same file! Therefore OEXCL isn't as\nexclusive as you might wish.\n\nSee also perlopentut.\n\nWhy do I sometimes get an \"Argument list too long\" when I use <*>?\nThe \"<>\" operator performs a globbing operation (see above). In Perl\nversions earlier than v5.6.0, the internal glob() operator forks csh(1)\nto do the actual glob expansion, but csh can't handle more than 127\nitems and so gives the error message \"Argument list too long\". People\nwho installed tcsh as csh won't have this problem, but their users may\nbe surprised by it.\n\nTo get around this, either upgrade to Perl v5.6.0 or later, do the glob\nyourself with readdir() and patterns, or use a module like File::Glob,\none that doesn't use the shell to do globbing.\n\nHow can I open a file named with a leading \">\" or trailing blanks?\n(contributed by Brian McCauley)\n\nThe special two-argument form of Perl's open() function ignores trailing\nblanks in filenames and infers the mode from certain leading characters\n(or a trailing \"|\"). In older versions of Perl this was the only version\nof open() and so it is prevalent in old code and books.\n\nUnless you have a particular reason to use the two-argument form you\nshould use the three-argument form of open() which does not treat any\ncharacters in the filename as special.\n\nopen my $fh, \"<\", \"  file  \";  # filename is \"   file   \"\nopen my $fh, \">\", \">file\";     # filename is \">file\"\n\nHow can I reliably rename a file?\nIf your operating system supports a proper mv(1) utility or its\nfunctional equivalent, this works:\n\nrename($old, $new) or system(\"mv\", $old, $new);\n\nIt may be more portable to use the File::Copy module instead. You just\ncopy to the new file to the new name (checking return values), then\ndelete the old one. This isn't really the same semantically as a",
            "subsections": [
                {
                    "name": "rename",
                    "content": "inode info, etc.\n\nHow can I lock a file?\nPerl's builtin flock() function (see perlfunc for details) will call"
                },
                {
                    "name": "flock",
                    "content": "and later), and lockf(3) if neither of the two previous system calls\nexists. On some systems, it may even use a different form of native\nlocking. Here are some gotchas with Perl's flock():\n\n1   Produces a fatal error if none of the three system calls (or their\nclose equivalent) exists.\n\n2   lockf(3) does not provide shared locking, and requires that the\nfilehandle be open for writing (or appending, or read/writing).\n\n3   Some versions of flock() can't lock files over a network (e.g. on\nNFS file systems), so you'd need to force the use of fcntl(2) when\nyou build Perl. But even this is dubious at best. See the flock\nentry of perlfunc and the INSTALL file in the source distribution\nfor information on building Perl to do this.\n\nTwo potentially non-obvious but traditional flock semantics are that\nit waits indefinitely until the lock is granted, and that its locks\nare *merely advisory*. Such discretionary locks are more flexible,\nbut offer fewer guarantees. This means that files locked with\nflock() may be modified by programs that do not also use flock().\nCars that stop for red lights get on well with each other, but not\nwith cars that don't stop for red lights. See the perlport manpage,\nyour port's specific documentation, or your system-specific local\nmanpages for details. It's best to assume traditional behavior if\nyou're writing portable programs. (If you're not, you should as\nalways feel perfectly free to write for your own system's\nidiosyncrasies (sometimes called \"features\"). Slavish adherence to\nportability concerns shouldn't get in the way of your getting your\njob done.)\n\nFor more information on file locking, see also \"File Locking\" in\nperlopentut if you have it (new for 5.6).\n\nWhy can't I just open(FH, \">file.lock\")?\nA common bit of code NOT TO USE is this:\n\nsleep(3) while -e 'file.lock';    # PLEASE DO NOT USE\nopen my $lock, '>', 'file.lock'; # THIS BROKEN CODE\n\nThis is a classic race condition: you take two steps to do something\nwhich must be done in one. That's why computer hardware provides an\natomic test-and-set instruction. In theory, this \"ought\" to work:\n\nsysopen my $fh, \"file.lock\", OWRONLY|OEXCL|OCREAT\nor die \"can't open  file.lock: $!\";\n\nexcept that lamentably, file creation (and deletion) is not atomic over\nNFS, so this won't work (at least, not every time) over the net. Various\nschemes involving link() have been suggested, but these tend to involve\nbusy-wait, which is also less than desirable.\n\nI still don't get locking. I just want to increment the number in the file. How can I do this?\nDidn't anyone ever tell you web-page hit counters were useless? They\ndon't count number of hits, they're a waste of time, and they serve only\nto stroke the writer's vanity. It's better to pick a random number;\nthey're more realistic.\n\nAnyway, this is what you can do if you can't help yourself.\n\nuse Fcntl qw(:DEFAULT :flock);\nsysopen my $fh, \"numfile\", ORDWR|OCREAT or die \"can't open numfile: $!\";\nflock $fh, LOCKEX                        or die \"can't flock numfile: $!\";\nmy $num = <$fh> || 0;\nseek $fh, 0, 0                            or die \"can't rewind numfile: $!\";\ntruncate $fh, 0                           or die \"can't truncate numfile: $!\";\n(print $fh $num+1, \"\\n\")                  or die \"can't write numfile: $!\";\nclose $fh                                 or die \"can't close numfile: $!\";\n\nHere's a much better web-page hit counter:\n\n$hits = int( (time() - 850000000) / rand(1000) );\n\nIf the count doesn't impress your friends, then the code might. :-)\n\nAll I want to do is append a small amount of text to the end of a file. Do I still have to use locking?\nIf you are on a system that correctly implements \"flock\" and you use the\nexample appending code from \"perldoc -f flock\" everything will be OK\neven if the OS you are on doesn't implement append mode correctly (if\nsuch a system exists). So if you are happy to restrict yourself to OSs\nthat implement \"flock\" (and that's not really much of a restriction)\nthen that is what you should do.\n\nIf you know you are only going to use a system that does correctly\nimplement appending (i.e. not Win32) then you can omit the \"seek\" from\nthe code in the previous answer.\n\nIf you know you are only writing code to run on an OS and filesystem\nthat does implement append mode correctly (a local filesystem on a\nmodern Unix for example), and you keep the file in block-buffered mode\nand you write less than one buffer-full of output between each manual\nflushing of the buffer then each bufferload is almost guaranteed to be\nwritten to the end of the file in one chunk without getting intermingled\nwith anyone else's output. You can also use the \"syswrite\" function\nwhich is simply a wrapper around your system's write(2) system call.\n\nThere is still a small theoretical chance that a signal will interrupt\nthe system-level write() operation before completion. There is also a\npossibility that some STDIO implementations may call multiple system\nlevel write()s even if the buffer was empty to start. There may be some\nsystems where this probability is reduced to zero, and this is not a\nconcern when using \":perlio\" instead of your system's STDIO.\n\nHow do I randomly update a binary file?\nIf you're just trying to patch a binary, in many cases something as\nsimple as this works:\n\nperl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs\n\nHowever, if you have fixed sized records, then you might do something\nmore like this:\n\nmy $RECSIZE = 220; # size of record, in bytes\nmy $recno   = 37;  # which record to update\nopen my $fh, '+<', 'somewhere' or die \"can't update somewhere: $!\";\nseek $fh, $recno * $RECSIZE, 0;\nread $fh, $record, $RECSIZE == $RECSIZE or die \"can't read record $recno: $!\";\n# munge the record\nseek $fh, -$RECSIZE, 1;\nprint $fh $record;\nclose $fh;\n\nLocking and error checking are left as an exercise for the reader. Don't\nforget them or you'll be quite sorry.\n\nHow do I get a file's timestamp in perl?\nIf you want to retrieve the time at which the file was last read,\nwritten, or had its meta-data (owner, etc) changed, you use the -A, -M,\nor -C file test operations as documented in perlfunc. These retrieve the\nage of the file (measured against the start-time of your program) in\ndays as a floating point number. Some platforms may not have all of\nthese times. See perlport for details. To retrieve the \"raw\" time in\nseconds since the epoch, you would call the stat function, then use"
                },
                {
                    "name": "localtime",
                    "content": "human-readable form.\n\nHere's an example:\n\nmy $writesecs = (stat($file))[9];\nprintf \"file %s updated at %s\\n\", $file,\nscalar localtime($writesecs);\n\nIf you prefer something more legible, use the File::stat module (part of\nthe standard distribution in version 5.004 and later):\n\n# error checking left as an exercise for reader.\nuse File::stat;\nuse Time::localtime;\nmy $datestring = ctime(stat($file)->mtime);\nprint \"file $file updated at $datestring\\n\";\n\nThe POSIX::strftime() approach has the benefit of being, in theory,\nindependent of the current locale. See perllocale for details.\n\nHow do I set a file's timestamp in perl?\nYou use the utime() function documented in \"utime\" in perlfunc. By way\nof example, here's a little program that copies the read and write times\nfrom its first argument to all the rest of them.\n\nif (@ARGV < 2) {\ndie \"usage: cptimes timestampfile otherfiles ...\\n\";\n}\nmy $timestamp = shift;\nmy($atime, $mtime) = (stat($timestamp))[8,9];\nutime $atime, $mtime, @ARGV;\n\nError checking is, as usual, left as an exercise for the reader.\n\nThe perldoc for utime also has an example that has the same effect as"
                },
                {
                    "name": "touch",
                    "content": "Certain file systems have a limited ability to store the times on a file\nat the expected level of precision. For example, the FAT and HPFS\nfilesystem are unable to create dates on files with a finer granularity\nthan two seconds. This is a limitation of the filesystems, not of"
                },
                {
                    "name": "utime",
                    "content": "How do I print to more than one file at once?\nTo connect one filehandle to several output filehandles, you can use the\nIO::Tee or Tie::FileHandle::Multiplex modules.\n\nIf you only have to do this once, you can print individually to each\nfilehandle.\n\nfor my $fh ($fh1, $fh2, $fh3) { print $fh \"whatever\\n\" }\n\nHow can I read in an entire file all at once?\nThe customary Perl approach for processing all the lines in a file is to\ndo so one line at a time:\n\nopen my $input, '<', $file or die \"can't open $file: $!\";\nwhile (<$input>) {\nchomp;\n# do something with $\n}\nclose $input or die \"can't close $file: $!\";\n\nThis is tremendously more efficient than reading the entire file into\nmemory as an array of lines and then processing it one element at a\ntime, which is often--if not almost always--the wrong approach. Whenever\nyou see someone do this:\n\nmy @lines = <INPUT>;\n\nYou should think long and hard about why you need everything loaded at\nonce. It's just not a scalable solution.\n\nIf you \"mmap\" the file with the File::Map module from CPAN, you can\nvirtually load the entire file into a string without actually storing it\nin memory:\n\nuse File::Map qw(mapfile);\n\nmapfile my $string, $filename;\n\nOnce mapped, you can treat $string as you would any other string. Since\nyou don't necessarily have to load the data, mmap-ing can be very fast\nand may not increase your memory footprint.\n\nYou might also find it more fun to use the standard Tie::File module, or\nthe DBFile module's $DBRECNO bindings, which allow you to tie an array\nto a file so that accessing an element of the array actually accesses\nthe corresponding line in the file.\n\nIf you want to load the entire file, you can use the Path::Tiny module\nto do it in one simple and efficient step:\n\nuse Path::Tiny;\n\nmy $allofit = path($filename)->slurp; # entire file in scalar\nmy @alllines = path($filename)->lines; # one line per element\n\nOr you can read the entire file contents into a scalar like this:\n\nmy $var;\n{\nlocal $/;\nopen my $fh, '<', $file or die \"can't open $file: $!\";\n$var = <$fh>;\n}\n\nThat temporarily undefs your record separator, and will automatically\nclose the file at block exit. If the file is already open, just use\nthis:\n\nmy $var = do { local $/; <$fh> };\n\nYou can also use a localized @ARGV to eliminate the \"open\":\n\nmy $var = do { local( @ARGV, $/ ) = $file; <> };\n\nHow can I read in a file by paragraphs?\nUse the $/ variable (see perlvar for details). You can either set it to\n\"\" to eliminate empty paragraphs (\"abc\\n\\n\\n\\ndef\", for instance, gets\ntreated as two paragraphs and not three), or \"\\n\\n\" to accept empty\nparagraphs.\n\nNote that a blank line must have no blanks in it. Thus\n\"fred\\n \\nstuff\\n\\n\" is one paragraph, but \"fred\\n\\nstuff\\n\\n\" is two.\n\nHow can I read a single character from a file? From the keyboard?\nYou can use the builtin getc() function for most filehandles, but it\nwon't (easily) work on a terminal device. For STDIN, either use the\nTerm::ReadKey module from CPAN or use the sample code in \"getc\" in\nperlfunc.\n\nIf your system supports the portable operating system programming\ninterface (POSIX), you can use the following code, which you'll note\nturns off echo processing as well.\n\n#!/usr/bin/perl -w\nuse strict;\n$| = 1;\nfor (1..4) {\nprint \"gimme: \";\nmy $got = getone();\nprint \"--> $got\\n\";\n}\nexit;\n\nBEGIN {\nuse POSIX qw(:termiosh);\n\nmy ($term, $oterm, $echo, $noecho, $fdstdin);\n\nmy $fdstdin = fileno(STDIN);\n\n$term     = POSIX::Termios->new();\n$term->getattr($fdstdin);\n$oterm     = $term->getlflag();\n\n$echo     = ECHO | ECHOK | ICANON;\n$noecho   = $oterm & ~$echo;\n\nsub cbreak {\n$term->setlflag($noecho);\n$term->setcc(VTIME, 1);\n$term->setattr($fdstdin, TCSANOW);\n}\n\nsub cooked {\n$term->setlflag($oterm);\n$term->setcc(VTIME, 0);\n$term->setattr($fdstdin, TCSANOW);\n}\n\nsub getone {\nmy $key = '';\ncbreak();\nsysread(STDIN, $key, 1);\ncooked();\nreturn $key;\n}\n}\n\nEND { cooked() }\n\nThe Term::ReadKey module from CPAN may be easier to use. Recent versions\ninclude also support for non-portable systems as well.\n\nuse Term::ReadKey;\nopen my $tty, '<', '/dev/tty';\nprint \"Gimme a char: \";\nReadMode \"raw\";\nmy $key = ReadKey 0, $tty;\nReadMode \"normal\";\nprintf \"\\nYou said %s, char number %03d\\n\",\n$key, ord $key;\n\nHow can I tell whether there's a character waiting on a filehandle?\nThe very first thing you should do is look into getting the\nTerm::ReadKey extension from CPAN. As we mentioned earlier, it now even\nhas limited support for non-portable (read: not open systems, closed,\nproprietary, not POSIX, not Unix, etc.) systems.\n\nYou should also check out the Frequently Asked Questions list in\ncomp.unix.* for things like this: the answer is essentially the same.\nIt's very system-dependent. Here's one solution that works on BSD\nsystems:\n\nsub keyready {\nmy($rin, $nfd);\nvec($rin, fileno(STDIN), 1) = 1;\nreturn $nfd = select($rin,undef,undef,0);\n}\n\nIf you want to find out how many characters are waiting, there's also\nthe FIONREAD ioctl call to be looked at. The *h2ph* tool that comes with\nPerl tries to convert C include files to Perl code, which can be\n\"require\"d. FIONREAD ends up defined as a function in the *sys/ioctl.ph*\nfile:\n\nrequire './sys/ioctl.ph';\n\n$size = pack(\"L\", 0);\nioctl(FH, FIONREAD(), $size)    or die \"Couldn't call ioctl: $!\\n\";\n$size = unpack(\"L\", $size);\n\nIf *h2ph* wasn't installed or doesn't work for you, you can *grep* the\ninclude files by hand:\n\n% grep FIONREAD /usr/include/*/*\n/usr/include/asm/ioctls.h:#define FIONREAD      0x541B\n\nOr write a small C program using the editor of champions:\n\n% cat > fionread.c\n#include <sys/ioctl.h>\nmain() {\nprintf(\"%#08x\\n\", FIONREAD);\n}\n^D\n% cc -o fionread fionread.c\n% ./fionread\n0x4004667f\n\nAnd then hard-code it, leaving porting as an exercise to your successor.\n\n$FIONREAD = 0x4004667f;         # XXX: opsys dependent\n\n$size = pack(\"L\", 0);\nioctl(FH, $FIONREAD, $size)     or die \"Couldn't call ioctl: $!\\n\";\n$size = unpack(\"L\", $size);\n\nFIONREAD requires a filehandle connected to a stream, meaning that\nsockets, pipes, and tty devices work, but *not* files.\n\nHow do I do a \"tail -f\" in perl?\nFirst try\n\nseek($gwfh, 0, 1);\n\nThe statement \"seek($gwfh, 0, 1)\" doesn't change the current position,\nbut it does clear the end-of-file condition on the handle, so that the\nnext \"<$gwfh>\" makes Perl try again to read something.\n\nIf that doesn't work (it relies on features of your stdio\nimplementation), then you need something more like this:\n\nfor (;;) {\nfor ($curpos = tell($gwfh); <$gwfh>; $curpos =tell($gwfh)) {\n# search for some stuff and put it into files\n}\n# sleep for a while\nseek($gwfh, $curpos, 0);  # seek to where we had been\n}\n\nIf this still doesn't work, look into the \"clearerr\" method from\nIO::Handle, which resets the error and end-of-file states on the handle.\n\nThere's also a File::Tail module from CPAN.\n\nHow do I dup() a filehandle in Perl?\nIf you check \"open\" in perlfunc, you'll see that several of the ways to\ncall open() should do the trick. For example:\n\nopen my $log, '>>', '/foo/logfile';\nopen STDERR, '>&', $log;\n\nOr even with a literal numeric descriptor:\n\nmy $fd = $ENV{MHCONTEXTFD};\nopen $mhcontext, \"<&=$fd\";  # like fdopen(3S)\n\nNote that \"<&STDIN\" makes a copy, but \"<&=STDIN\" makes an alias. That\nmeans if you close an aliased handle, all aliases become inaccessible.\nThis is not true with a copied one.\n\nError checking, as always, has been left as an exercise for the reader.\n\nHow do I close a file descriptor by number?\nIf, for some reason, you have a file descriptor instead of a filehandle\n(perhaps you used \"POSIX::open\"), you can use the close() function from\nthe POSIX module:\n\nuse POSIX ();\n\nPOSIX::close( $fd );\n\nThis should rarely be necessary, as the Perl close() function is to be\nused for things that Perl opened itself, even if it was a dup of a\nnumeric descriptor as with \"MHCONTEXT\" above. But if you really have to,\nyou may be able to do this:\n\nrequire './sys/syscall.ph';\nmy $rc = syscall(SYSclose(), $fd + 0);  # must force numeric\ndie \"can't sysclose $fd: $!\" unless $rc == -1;\n\nOr, just use the fdopen(3S) feature of open():\n\n{\nopen my $fh, \"<&=$fd\" or die \"Cannot reopen fd=$fd: $!\";\nclose $fh;\n}\n\nWhy doesn't glob(\"*.*\") get all the files?\nBecause even on non-Unix ports, Perl's glob function follows standard\nUnix globbing semantics. You'll need glob(\"*\") to get all (non-hidden)\nfiles. This makes glob() portable even to legacy systems. Your port may\ninclude proprietary globbing functions as well. Check its documentation\nfor details.\n\nWhy does Perl let me delete read-only files? Why does \"-i\" clobber protected files? Isn't this a bug in Perl?\nThis is elaborately and painstakingly described in the file-dir-perms\narticle in the \"Far More Than You Ever Wanted To Know\" collection in\n<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> .\n\nThe executive summary: learn how your filesystem works. The permissions\non a file say what can happen to the data in that file. The permissions\non a directory say what can happen to the list of files in that\ndirectory. If you delete a file, you're removing its name from the\ndirectory (so the operation depends on the permissions of the directory,\nnot of the file). If you try to write to the file, the permissions of\nthe file govern whether you're allowed to.\n\nHow do I select a random line from a file?\nShort of loading the file into a database or pre-indexing the lines in\nthe file, there are a couple of things that you can do.\n\nHere's a reservoir-sampling algorithm from the Camel Book:\n\nsrand;\nrand($.) < 1 && ($line = $) while <>;\n\nThis has a significant advantage in space over reading the whole file\nin. You can find a proof of this method in *The Art of Computer\nProgramming*, Volume 2, Section 3.4.2, by Donald E. Knuth.\n\nYou can use the File::Random module which provides a function for that\nalgorithm:\n\nuse File::Random qw/randomline/;\nmy $line = randomline($filename);\n\nAnother way is to use the Tie::File module, which treats the entire file\nas an array. Simply access a random array element.\n\nWhy do I get weird spaces when I print an array of lines?\n(contributed by brian d foy)\n\nIf you are seeing spaces between the elements of your array when you\nprint the array, you are probably interpolating the array in double\nquotes:\n\nmy @animals = qw(camel llama alpaca vicuna);\nprint \"animals are: @animals\\n\";\n\nIt's the double quotes, not the \"print\", doing this. Whenever you\ninterpolate an array in a double quote context, Perl joins the elements\nwith spaces (or whatever is in $\", which is a space by default):\n\nanimals are: camel llama alpaca vicuna\n\nThis is different than printing the array without the interpolation:\n\nmy @animals = qw(camel llama alpaca vicuna);\nprint \"animals are: \", @animals, \"\\n\";\n\nNow the output doesn't have the spaces between the elements because the\nelements of @animals simply become part of the list to \"print\":\n\nanimals are: camelllamaalpacavicuna\n\nYou might notice this when each of the elements of @array end with a\nnewline. You expect to print one element per line, but notice that every\nline after the first is indented:\n\nthis is a line\nthis is another line\nthis is the third line\n\nThat extra space comes from the interpolation of the array. If you don't\nwant to put anything between your array elements, don't use the array in\ndouble quotes. You can send it to print without them:\n\nprint @lines;\n\nHow do I delete a directory tree?\n(contributed by brian d foy)\n\nIf you have an empty directory, you can use Perl's built-in \"rmdir\". If\nthe directory is not empty (so, with files or subdirectories), you\neither have to empty it yourself (a lot of work) or use a module to help\nyou.\n\nThe File::Path module, which comes with Perl, has a \"removetree\" which\ncan take care of all of the hard work for you:\n\nuse File::Path qw(removetree);\n\nremovetree( @directories );\n\nThe File::Path module also has a legacy interface to the older \"rmtree\"\nsubroutine.\n"
                }
            ]
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq6.pod": {
            "content": "How can I hope to use regular expressions without creating illegible and unmaintainable code?\nThree techniques can make regular expressions maintainable and\nunderstandable.\n\nComments Outside the Regex\nDescribe what you're doing and how you're doing it, using normal\nPerl comments.\n\n# turn the line into the first word, a colon, and the\n# number of characters on the rest of the line\ns/^(\\w+)(.*)/ lc($1) . \":\" . length($2) /meg;\n\nComments Inside the Regex\nThe \"/x\" modifier causes whitespace to be ignored in a regex pattern\n(except in a character class and a few other places), and also\nallows you to use normal comments there, too. As you can imagine,\nwhitespace and comments help a lot.\n\n\"/x\" lets you turn this:\n\ns{<(?:[^>'\"]*|\".*?\"|'.*?')+>}{}gs;\n\ninto this:\n\ns{ <                    # opening angle bracket\n(?:                 # Non-backreffing grouping paren\n[^>'\"] *        # 0 or more things that are neither > nor ' nor \"\n|           #    or else\n\".*?\"           # a section between double quotes (stingy match)\n|           #    or else\n'.*?'           # a section between single quotes (stingy match)\n) +                 #   all occurring one or more times\n>                   # closing angle bracket\n}{}gsx;                 # replace with nothing, i.e. delete\n\nIt's still not quite so clear as prose, but it is very useful for\ndescribing the meaning of each part of the pattern.\n\nDifferent Delimiters\nWhile we normally think of patterns as being delimited with \"/\"\ncharacters, they can be delimited by almost any character. perlre\ndescribes this. For example, the \"s///\" above uses braces as\ndelimiters. Selecting another delimiter can avoid quoting the\ndelimiter within the pattern:\n\ns/\\/usr\\/local/\\/usr\\/share/g;    # bad delimiter choice\ns#/usr/local#/usr/share#g;        # better\n\nUsing logically paired delimiters can be even more readable:\n\ns{/usr/local/}{/usr/share}g;      # better still\n\nI'm having trouble matching over more than one line. What's wrong?\nEither you don't have more than one line in the string you're looking at\n(probably), or else you aren't using the correct modifier(s) on your\npattern (possibly).\n\nThere are many ways to get multiline data into a string. If you want it\nto happen automatically while reading input, you'll want to set $/\n(probably to '' for paragraphs or \"undef\" for the whole file) to allow\nyou to read more than one line at a time.\n\nRead perlre to help you decide which of \"/s\" and \"/m\" (or both) you\nmight want to use: \"/s\" allows dot to include newline, and \"/m\" allows\ncaret and dollar to match next to a newline, not just at the end of the\nstring. You do need to make sure that you've actually got a multiline\nstring in there.\n\nFor example, this program detects duplicate words, even when they span\nline breaks (but not paragraph ones). For this example, we don't need\n\"/s\" because we aren't using dot in a regular expression that we want to\ncross line boundaries. Neither do we need \"/m\" because we don't want\ncaret or dollar to match at any point inside the record next to\nnewlines. But it's imperative that $/ be set to something other than the\ndefault, or else we won't actually ever have a multiline record read in.\n\n$/ = '';          # read in whole paragraph, not just one line\nwhile ( <> ) {\nwhile ( /\\b([\\w'-]+)(\\s+\\g1)+\\b/gi ) {     # word starts alpha\nprint \"Duplicate $1 at paragraph $.\\n\";\n}\n}\n\nHere's some code that finds sentences that begin with \"From \" (which\nwould be mangled by many mailers):\n\n$/ = '';          # read in whole paragraph, not just one line\nwhile ( <> ) {\nwhile ( /^From /gm ) { # /m makes ^ match next to \\n\nprint \"leading From in paragraph $.\\n\";\n}\n}\n\nHere's code that finds everything between START and END in a paragraph:\n\nundef $/;          # read in whole file, not just one line or paragraph\nwhile ( <> ) {\nwhile ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries\nprint \"$1\\n\";\n}\n}\n\nHow can I pull out lines between two patterns that are themselves on different lines?\nYou can use Perl's somewhat exotic \"..\" operator (documented in perlop):\n\nperl -ne 'print if /START/ .. /END/' file1 file2 ...\n\nIf you wanted text and not lines, you would use\n\nperl -0777 -ne 'print \"$1\\n\" while /START(.*?)END/gs' file1 file2 ...\n\nBut if you want nested occurrences of \"START\" through \"END\", you'll run\nup against the problem described in the question in this section on\nmatching balanced text.\n\nHere's another example of using \"..\":\n\nwhile (<>) {\nmy $inheader =   1  .. /^$/;\nmy $inbody   = /^$/ .. eof;\n# now choose between them\n} continue {\n$. = 0 if eof;    # fix $.\n}\n\nHow do I match XML, HTML, or other nasty, ugly things with a regex?\nDo not use regexes. Use a module and forget about the regular\nexpressions. The XML::LibXML, HTML::TokeParser and HTML::TreeBuilder\nmodules are good starts, although each namespace has other parsing\nmodules specialized for certain tasks and different ways of doing it.\nStart at CPAN Search ( <http://metacpan.org/> ) and wonder at all the\nwork people have done for you already! :)\n\nI put a regular expression into $/ but it didn't work. What's wrong?\n$/ has to be a string. You can use these examples if you really need to\ndo this.\n\nIf you have File::Stream, this is easy.\n\nuse File::Stream;\n\nmy $stream = File::Stream->new(\n$filehandle,\nseparator => qr/\\s*,\\s*/,\n);\n\nprint \"$\\n\" while <$stream>;\n\nIf you don't have File::Stream, you have to do a little more work.\n\nYou can use the four-argument form of sysread to continually add to a\nbuffer. After you add to the buffer, you check if you have a complete\nline (using your regular expression).\n\nlocal $ = \"\";\nwhile( sysread FH, $, 8192, length ) {\nwhile( s/^((?s).*?)yourpattern// ) {\nmy $record = $1;\n# do stuff here.\n}\n}\n\nYou can do the same thing with foreach and a match using the c flag and\nthe \\G anchor, if you do not mind your entire file being in memory at\nthe end.\n\nlocal $ = \"\";\nwhile( sysread FH, $, 8192, length ) {\nforeach my $record ( m/\\G((?s).*?)yourpattern/gc ) {\n# do stuff here.\n}\nsubstr( $, 0, pos ) = \"\" if pos;\n}\n\nHow do I substitute case-insensitively on the LHS while preserving case on the RHS?\nHere's a lovely Perlish solution by Larry Rosler. It exploits properties\nof bitwise xor on ASCII strings.\n\n$= \"this is a TEsT case\";\n\n$old = 'test';\n$new = 'success';\n\ns{(\\Q$old\\E)}\n{ uc $new | (uc $1 ^ $1) .\n(uc(substr $1, -1) ^ substr $1, -1) x\n(length($new) - length $1)\n}egi;\n\nprint;\n\nAnd here it is as a subroutine, modeled after the above:\n\nsub preservecase {\nmy ($old, $new) = @;\nmy $mask = uc $old ^ $old;\n\nuc $new | $mask .\nsubstr($mask, -1) x (length($new) - length($old))\n}\n\n$string = \"this is a TEsT case\";\n$string =~ s/(test)/preservecase($1, \"success\")/egi;\nprint \"$string\\n\";\n\nThis prints:\n\nthis is a SUcCESS case\n\nAs an alternative, to keep the case of the replacement word if it is\nlonger than the original, you can use this code, by Jeff Pinyan:\n\nsub preservecase {\nmy ($from, $to) = @;\nmy ($lf, $lt) = map length, @;\n\nif ($lt < $lf) { $from = substr $from, 0, $lt }\nelse { $from .= substr $to, $lf }\n\nreturn uc $to | ($from ^ uc $from);\n}\n\nThis changes the sentence to \"this is a SUcCess case.\"\n\nJust to show that C programmers can write C in any programming language,\nif you prefer a more C-like solution, the following script makes the\nsubstitution have the same case, letter by letter, as the original. (It\nalso happens to run about 240% slower than the Perlish solution runs.)\nIf the substitution has more characters than the string being\nsubstituted, the case of the last character is used for the rest of the\nsubstitution.\n\n# Original by Nathan Torkington, massaged by Jeffrey Friedl\n#\nsub preservecase\n{\nmy ($old, $new) = @;\nmy $state = 0; # 0 = no change; 1 = lc; 2 = uc\nmy ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));\nmy $len = $oldlen < $newlen ? $oldlen : $newlen;\n\nfor ($i = 0; $i < $len; $i++) {\nif ($c = substr($old, $i, 1), $c =~ /[\\W\\d]/) {\n$state = 0;\n} elsif (lc $c eq $c) {\nsubstr($new, $i, 1) = lc(substr($new, $i, 1));\n$state = 1;\n} else {\nsubstr($new, $i, 1) = uc(substr($new, $i, 1));\n$state = 2;\n}\n}\n# finish up with any remaining new (for when new is longer than old)\nif ($newlen > $oldlen) {\nif ($state == 1) {\nsubstr($new, $oldlen) = lc(substr($new, $oldlen));\n} elsif ($state == 2) {\nsubstr($new, $oldlen) = uc(substr($new, $oldlen));\n}\n}\nreturn $new;\n}\n\nHow can I make \"\\w\" match national character sets?\nPut \"use locale;\" in your script. The \\w character class is taken from\nthe current locale.\n\nSee perllocale for details.\n\nHow can I match a locale-smart version of \"/[a-zA-Z]/\"?\nYou can use the POSIX character class syntax \"/[[:alpha:]]/\" documented\nin perlre.\n\nNo matter which locale you are in, the alphabetic characters are the\ncharacters in \\w without the digits and the underscore. As a regex, that\nlooks like \"/[^\\W\\d]/\". Its complement, the non-alphabetics, is then\neverything in \\W along with the digits and the underscore, or\n\"/[\\W\\d]/\".\n\nHow can I quote a variable to use in a regex?\nThe Perl parser will expand $variable and @variable references in\nregular expressions unless the delimiter is a single quote. Remember,\ntoo, that the right-hand side of a \"s///\" substitution is considered a\ndouble-quoted string (see perlop for more details). Remember also that\nany regex special characters will be acted on unless you precede the\nsubstitution with \\Q. Here's an example:\n\n$string = \"Placido P. Octopus\";\n$regex  = \"P.\";\n\n$string =~ s/$regex/Polyp/;\n# $string is now \"Polypacido P. Octopus\"\n\nBecause \".\" is special in regular expressions, and can match any single\ncharacter, the regex \"P.\" here has matched the <Pl> in the original\nstring.\n\nTo escape the special meaning of \".\", we use \"\\Q\":\n\n$string = \"Placido P. Octopus\";\n$regex  = \"P.\";\n\n$string =~ s/\\Q$regex/Polyp/;\n# $string is now \"Placido Polyp Octopus\"\n\nThe use of \"\\Q\" causes the \".\" in the regex to be treated as a regular\ncharacter, so that \"P.\" matches a \"P\" followed by a dot.\n\nWhat is \"/o\" really for?\n(contributed by brian d foy)\n\nThe \"/o\" option for regular expressions (documented in perlop and\nperlreref) tells Perl to compile the regular expression only once. This\nis only useful when the pattern contains a variable. Perls 5.6 and later\nhandle this automatically if the pattern does not change.\n\nSince the match operator \"m//\", the substitution operator \"s///\", and\nthe regular expression quoting operator \"qr//\" are double-quotish\nconstructs, you can interpolate variables into the pattern. See the\nanswer to \"How can I quote a variable to use in a regex?\" for more\ndetails.\n\nThis example takes a regular expression from the argument list and\nprints the lines of input that match it:\n\nmy $pattern = shift @ARGV;\n\nwhile( <> ) {\nprint if m/$pattern/;\n}\n\nVersions of Perl prior to 5.6 would recompile the regular expression for\neach iteration, even if $pattern had not changed. The \"/o\" would prevent\nthis by telling Perl to compile the pattern the first time, then reuse\nthat for subsequent iterations:\n\nmy $pattern = shift @ARGV;\n\nwhile( <> ) {\nprint if m/$pattern/o; # useful for Perl < 5.6\n}\n\nIn versions 5.6 and later, Perl won't recompile the regular expression\nif the variable hasn't changed, so you probably don't need the \"/o\"\noption. It doesn't hurt, but it doesn't help either. If you want any\nversion of Perl to compile the regular expression only once even if the\nvariable changes (thus, only using its initial value), you still need\nthe \"/o\".\n\nYou can watch Perl's regular expression engine at work to verify for\nyourself if Perl is recompiling a regular expression. The use re 'debug'\npragma (comes with Perl 5.005 and later) shows the details. With Perls\nbefore 5.6, you should see \"re\" reporting that its compiling the regular\nexpression on each iteration. With Perl 5.6 or later, you should only\nsee \"re\" report that for the first iteration.\n\nuse re 'debug';\n\nmy $regex = 'Perl';\nforeach ( qw(Perl Java Ruby Python) ) {\nprint STDERR \"-\" x 73, \"\\n\";\nprint STDERR \"Trying $...\\n\";\nprint STDERR \"\\t$ is good!\\n\" if m/$regex/;\n}\n\nHow do I use a regular expression to strip C-style comments from a file?\nWhile this actually can be done, it's much harder than you'd think. For\nexample, this one-liner\n\nperl -0777 -pe 's{/\\*.*?\\*/}{}gs' foo.c\n\nwill work in many but not all cases. You see, it's too simple-minded for\ncertain kinds of C programs, in particular, those with what appear to be\ncomments in quoted strings. For that, you'd need something like this,\ncreated by Jeffrey Friedl and later modified by Fred Curtis.\n\n$/ = undef;\n$ = <>;\ns#/\\*[^*]*\\*+([^/*][^*]*\\*+)*/|(\"(\\\\.|[^\"\\\\])*\"|'(\\\\.|[^'\\\\])*'|.[^/\"'\\\\]*)#defined $2 ? $2 : \"\"#gse;\nprint;\n\nThis could, of course, be more legibly written with the \"/x\" modifier,\nadding whitespace and comments. Here it is expanded, courtesy of Fred\nCurtis.\n\ns{\n/\\*         ##  Start of /* ... */ comment\n[^*]*\\*+    ##  Non-* followed by 1-or-more *'s\n(\n[^/*][^*]*\\*+\n)*          ##  0-or-more things which don't start with /\n##    but do end with '*'\n/           ##  End of /* ... */ comment\n\n|         ##     OR  various things which aren't comments:\n\n(\n\"           ##  Start of \" ... \" string\n(\n\\\\.           ##  Escaped char\n|               ##    OR\n[^\"\\\\]        ##  Non \"\\\n)*\n\"           ##  End of \" ... \" string\n\n|         ##     OR\n\n'           ##  Start of ' ... ' string\n(\n\\\\.           ##  Escaped char\n|               ##    OR\n[^'\\\\]        ##  Non '\\\n)*\n'           ##  End of ' ... ' string\n\n|         ##     OR\n\n.           ##  Anything other char\n[^/\"'\\\\]*   ##  Chars which doesn't start a comment, string or escape\n)\n}{defined $2 ? $2 : \"\"}gxse;\n\nA slight modification also removes C++ comments, possibly spanning\nmultiple lines using a continuation character:\n\ns#/\\*[^*]*\\*+([^/*][^*]*\\*+)*/|//([^\\\\]|[^\\n][\\n]?)*?\\n|(\"(\\\\.|[^\"\\\\])*\"|'(\\\\.|[^'\\\\])*'|.[^/\"'\\\\]*)#defined $3 ? $3 : \"\"#gse;\n\nCan I use Perl regular expressions to match balanced text?\n(contributed by brian d foy)\n\nYour first try should probably be the Text::Balanced module, which is in\nthe Perl standard library since Perl 5.8. It has a variety of functions\nto deal with tricky text. The Regexp::Common module can also help by\nproviding canned patterns you can use.\n\nAs of Perl 5.10, you can match balanced text with regular expressions\nusing recursive patterns. Before Perl 5.10, you had to resort to various\ntricks such as using Perl code in \"(??{})\" sequences.\n\nHere's an example using a recursive regular expression. The goal is to\ncapture all of the text within angle brackets, including the text in\nnested angle brackets. This sample text has two \"major\" groups: a group\nwith one level of nesting and a group with two levels of nesting. There\nare five total groups in angle brackets:\n\nI have some <brackets in <nested brackets> > and\n<another group <nested once <nested twice> > >\nand that's it.\n\nThe regular expression to match the balanced text uses two new (to Perl\n5.10) regular expression features. These are covered in perlre and this\nexample is a modified version of one in that documentation.\n\nFirst, adding the new possessive \"+\" to any quantifier finds the longest\nmatch and does not backtrack. That's important since you want to handle\nany angle brackets through the recursion, not backtracking. The group\n\"[^<>]++\" finds one or more non-angle brackets without backtracking.\n\nSecond, the new \"(?PARNO)\" refers to the sub-pattern in the particular\ncapture group given by \"PARNO\". In the following regex, the first\ncapture group finds (and remembers) the balanced text, and you need that\nsame pattern within the first buffer to get past the nested text. That's\nthe recursive part. The \"(?1)\" uses the pattern in the outer capture\ngroup as an independent part of the regex.\n\nPutting it all together, you have:\n\n#!/usr/local/bin/perl5.10.0\n\nmy $string =<<\"HERE\";\nI have some <brackets in <nested brackets> > and\n<another group <nested once <nested twice> > >\nand that's it.\nHERE\n\nmy @groups = $string =~ m/\n(                   # start of capture group 1\n<                   # match an opening angle bracket\n(?:\n[^<>]++     # one or more non angle brackets, non backtracking\n|\n(?1)        # found < or >, so recurse to capture group 1\n)*\n>                   # match a closing angle bracket\n)                   # end of capture group 1\n/xg;\n\n$\" = \"\\n\\t\";\nprint \"Found:\\n\\t@groups\\n\";\n\nThe output shows that Perl found the two major groups:\n\nFound:\n<brackets in <nested brackets> >\n<another group <nested once <nested twice> > >\n\nWith a little extra work, you can get all of the groups in angle\nbrackets even if they are in other angle brackets too. Each time you get\na balanced match, remove its outer delimiter (that's the one you just\nmatched so don't match it again) and add it to a queue of strings to\nprocess. Keep doing that until you get no matches:\n\n#!/usr/local/bin/perl5.10.0\n\nmy @queue =<<\"HERE\";\nI have some <brackets in <nested brackets> > and\n<another group <nested once <nested twice> > >\nand that's it.\nHERE\n\nmy $regex = qr/\n(                   # start of bracket 1\n<                   # match an opening angle bracket\n(?:\n[^<>]++     # one or more non angle brackets, non backtracking\n|\n(?1)        # recurse to bracket 1\n)*\n>                   # match a closing angle bracket\n)                   # end of bracket 1\n/x;\n\n$\" = \"\\n\\t\";\n\nwhile( @queue ) {\nmy $string = shift @queue;\n\nmy @groups = $string =~ m/$regex/g;\nprint \"Found:\\n\\t@groups\\n\\n\" if @groups;\n\nunshift @queue, map { s/^<//; s/>$//; $ } @groups;\n}\n\nThe output shows all of the groups. The outermost matches show up first\nand the nested matches show up later:\n\nFound:\n<brackets in <nested brackets> >\n<another group <nested once <nested twice> > >\n\nFound:\n<nested brackets>\n\nFound:\n<nested once <nested twice> >\n\nFound:\n<nested twice>\n\nHow do I process each word on each line?\nUse the split function:\n\nwhile (<>) {\nforeach my $word ( split ) {\n# do something with $word here\n}\n}\n\nNote that this isn't really a word in the English sense; it's just\nchunks of consecutive non-whitespace characters.\n\nTo work with only alphanumeric sequences (including underscores), you\nmight consider\n\nwhile (<>) {\nforeach $word (m/(\\w+)/g) {\n# do something with $word here\n}\n}\n\nHow can I print out a word-frequency or line-frequency summary?\nTo do this, you have to parse out each word in the input stream. We'll\npretend that by word you mean chunk of alphabetics, hyphens, or\napostrophes, rather than the non-whitespace chunk idea of a word given\nin the previous question:\n\nmy (%seen);\nwhile (<>) {\nwhile ( /(\\b[^\\W\\d][\\w'-]+\\b)/g ) {   # misses \"`sheep'\"\n$seen{$1}++;\n}\n}\n\nwhile ( my ($word, $count) = each %seen ) {\nprint \"$count $word\\n\";\n}\n\nIf you wanted to do the same thing for lines, you wouldn't need a\nregular expression:\n\nmy (%seen);\n\nwhile (<>) {\n$seen{$}++;\n}\n\nwhile ( my ($line, $count) = each %seen ) {\nprint \"$count $line\";\n}\n\nIf you want these output in a sorted order, see perlfaq4: \"How do I sort\na hash (optionally by value instead of key)?\".\n\nHow do I efficiently match many regular expressions at once?\n(contributed by brian d foy)\n\nYou want to avoid compiling a regular expression every time you want to\nmatch it. In this example, perl must recompile the regular expression\nfor every iteration of the \"foreach\" loop since $pattern can change:\n\nmy @patterns = qw( fo+ ba[rz] );\n\nLINE: while( my $line = <> ) {\nforeach my $pattern ( @patterns ) {\nif( $line =~ m/\\b$pattern\\b/i ) {\nprint $line;\nnext LINE;\n}\n}\n}\n\nThe \"qr//\" operator compiles a regular expression, but doesn't apply it.\nWhen you use the pre-compiled version of the regex, perl does less work.\nIn this example, I inserted a \"map\" to turn each pattern into its\npre-compiled form. The rest of the script is the same, but faster:\n\nmy @patterns = map { qr/\\b$\\b/i } qw( fo+ ba[rz] );\n\nLINE: while( my $line = <> ) {\nforeach my $pattern ( @patterns ) {\nif( $line =~ m/$pattern/ ) {\nprint $line;\nnext LINE;\n}\n}\n}\n\nIn some cases, you may be able to make several patterns into a single\nregular expression. Beware of situations that require backtracking\nthough. In this example, the regex is only compiled once because $regex\ndoesn't change between iterations:\n\nmy $regex = join '|', qw( fo+ ba[rz] );\n\nwhile( my $line = <> ) {\nprint if $line =~ m/\\b(?:$regex)\\b/i;\n}\n\nThe function \"list2re\" in Data::Munge on CPAN can also be used to form a\nsingle regex that matches a list of literal strings (not regexes).\n\nFor more details on regular expression efficiency, see *Mastering\nRegular Expressions* by Jeffrey Friedl. He explains how the regular\nexpressions engine works and why some patterns are surprisingly\ninefficient. Once you understand how perl applies regular expressions,\nyou can tune them for individual situations.\n\nWhy does using $&, $`, or $' slow my program down?\n(contributed by Anno Siegel)\n\nOnce Perl sees that you need one of these variables anywhere in the\nprogram, it provides them on each and every pattern match. That means\nthat on every pattern match the entire string will be copied, part of it\nto $`, part to $&, and part to $'. Thus the penalty is most severe with\nlong strings and patterns that match often. Avoid $&, $', and $` if you\ncan, but if you can't, once you've used them at all, use them at will\nbecause you've already paid the price. Remember that some algorithms\nreally appreciate them. As of the 5.005 release, the $& variable is no\nlonger \"expensive\" the way the other two are.\n\nSince Perl 5.6.1 the special variables @- and @+ can functionally\nreplace $`, $& and $'. These arrays contain pointers to the beginning\nand end of each match (see perlvar for the full story), so they give you\nessentially the same information, but without the risk of excessive\nstring copying.\n\nPerl 5.10 added three specials, \"${^MATCH}\", \"${^PREMATCH}\", and\n\"${^POSTMATCH}\" to do the same job but without the global performance\npenalty. Perl 5.10 only sets these variables if you compile or execute\nthe regular expression with the \"/p\" modifier.\n\nWhat good is \"\\G\" in a regular expression?\nYou use the \"\\G\" anchor to start the next match on the same string where\nthe last match left off. The regular expression engine cannot skip over\nany characters to find the next match with this anchor, so \"\\G\" is\nsimilar to the beginning of string anchor, \"^\". The \"\\G\" anchor is\ntypically used with the \"g\" modifier. It uses the value of pos() as the\nposition to start the next match. As the match operator makes successive\nmatches, it updates pos() with the position of the next character past\nthe last match (or the first character of the next match, depending on\nhow you like to look at it). Each string has its own pos() value.\n\nSuppose you want to match all of consecutive pairs of digits in a string\nlike \"1122a44\" and stop matching when you encounter non-digits. You want\nto match 11 and 22 but the letter \"a\" shows up between 22 and 44 and you\nwant to stop at \"a\". Simply matching pairs of digits skips over the \"a\"\nand still matches 44.\n\n$ = \"1122a44\";\nmy @pairs = m/(\\d\\d)/g;   # qw( 11 22 44 )\n\nIf you use the \"\\G\" anchor, you force the match after 22 to start with\nthe \"a\". The regular expression cannot match there since it does not\nfind a digit, so the next match fails and the match operator returns the\npairs it already found.\n\n$ = \"1122a44\";\nmy @pairs = m/\\G(\\d\\d)/g; # qw( 11 22 )\n\nYou can also use the \"\\G\" anchor in scalar context. You still need the\n\"g\" modifier.\n\n$ = \"1122a44\";\nwhile( m/\\G(\\d\\d)/g ) {\nprint \"Found $1\\n\";\n}\n\nAfter the match fails at the letter \"a\", perl resets pos() and the next\nmatch on the same string starts at the beginning.\n\n$ = \"1122a44\";\nwhile( m/\\G(\\d\\d)/g ) {\nprint \"Found $1\\n\";\n}\n\nprint \"Found $1 after while\" if m/(\\d\\d)/g; # finds \"11\"\n\nYou can disable pos() resets on fail with the \"c\" modifier, documented\nin perlop and perlreref. Subsequent matches start where the last\nsuccessful match ended (the value of pos()) even if a match on the same\nstring has failed in the meantime. In this case, the match after the\nwhile() loop starts at the \"a\" (where the last match stopped), and since\nit does not use any anchor it can skip over the \"a\" to find 44.\n\n$ = \"1122a44\";\nwhile( m/\\G(\\d\\d)/gc ) {\nprint \"Found $1\\n\";\n}\n\nprint \"Found $1 after while\" if m/(\\d\\d)/g; # finds \"44\"\n\nTypically you use the \"\\G\" anchor with the \"c\" modifier when you want to\ntry a different match if one fails, such as in a tokenizer. Jeffrey\nFriedl offers this example which works in 5.004 or later.\n\nwhile (<>) {\nchomp;\nPARSER: {\nm/ \\G( \\d+\\b    )/gcx   && do { print \"number: $1\\n\";  redo; };\nm/ \\G( \\w+      )/gcx   && do { print \"word:   $1\\n\";  redo; };\nm/ \\G( \\s+      )/gcx   && do { print \"space:  $1\\n\";  redo; };\nm/ \\G( [^\\w\\d]+ )/gcx   && do { print \"other:  $1\\n\";  redo; };\n}\n}\n\nFor each line, the \"PARSER\" loop first tries to match a series of digits\nfollowed by a word boundary. This match has to start at the place the\nlast match left off (or the beginning of the string on the first match).\nSince \"m/ \\G( \\d+\\b )/gcx\" uses the \"c\" modifier, if the string does not\nmatch that regular expression, perl does not reset pos() and the next\nmatch starts at the same position to try a different pattern.\n\nAre Perl regexes DFAs or NFAs? Are they POSIX compliant?\nWhile it's true that Perl's regular expressions resemble the DFAs\n(deterministic finite automata) of the egrep(1) program, they are in\nfact implemented as NFAs (non-deterministic finite automata) to allow\nbacktracking and backreferencing. And they aren't POSIX-style either,\nbecause those guarantee worst-case behavior for all cases. (It seems\nthat some people prefer guarantees of consistency, even when what's\nguaranteed is slowness.) See the book \"Mastering Regular Expressions\"\n(from O'Reilly) by Jeffrey Friedl for all the details you could ever\nhope to know on these matters (a full citation appears in perlfaq2).\n\nHow can I match strings with multibyte characters?\nStarting from Perl 5.6 Perl has had some level of multibyte character\nsupport. Perl 5.8 or later is recommended. Supported multibyte character\nrepertoires include Unicode, and legacy encodings through the Encode\nmodule. See perluniintro, perlunicode, and Encode.\n\nIf you are stuck with older Perls, you can do Unicode with the\nUnicode::String module, and character conversions using the\nUnicode::Map8 and Unicode::Map modules. If you are using Japanese\nencodings, you might try using the jperl 5.00503.\n\nFinally, the following set of approaches was offered by Jeffrey Friedl,\nwhose article in issue #5 of The Perl Journal talks about this very\nmatter.\n\nLet's suppose you have some weird Martian encoding where pairs of ASCII\nuppercase letters encode single Martian letters (i.e. the two bytes \"CV\"\nmake a single Martian letter, as do the two bytes \"SG\", \"VS\", \"XX\",\netc.). Other bytes represent single characters, just like ASCII.\n\nSo, the string of Martian \"I am CVSGXX!\" uses 12 bytes to encode the\nnine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.\n\nNow, say you want to search for the single character \"/GX/\". Perl\ndoesn't know about Martian, so it'll find the two bytes \"GX\" in the \"I\nam CVSGXX!\" string, even though that character isn't there: it just\nlooks like it is because \"SG\" is next to \"XX\", but there's no real \"GX\".\nThis is a big problem.\n\nHere are a few ways, all painful, to deal with it:\n\n# Make sure adjacent \"martian\" bytes are no longer adjacent.\n$martian =~ s/([A-Z][A-Z])/ $1 /g;\n\nprint \"found GX!\\n\" if $martian =~ /GX/;\n\nOr like this:\n\nmy @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;\n# above is conceptually similar to:     my @chars = $text =~ m/(.)/g;\n#\nforeach my $char (@chars) {\nprint \"found GX!\\n\", last if $char eq 'GX';\n}\n\nOr like this:\n\nwhile ($martian =~ m/\\G([A-Z][A-Z]|.)/gs) {  # \\G probably unneeded\nif ($1 eq 'GX') {\nprint \"found GX!\\n\";\nlast;\n}\n}\n\nHere's another, slightly less painful, way to do it from Benjamin\nGoldberg, who uses a zero-width negative look-behind assertion.\n\nprint \"found GX!\\n\" if    $martian =~ m/\n(?<![A-Z])\n(?:[A-Z][A-Z])*?\nGX\n/x;\n\nThis succeeds if the \"martian\" character GX is in the string, and fails\notherwise. If you don't like using (?<!), a zero-width negative\nlook-behind assertion, you can replace (?<![A-Z]) with (?:^|[^A-Z]).\n\nIt does have the drawback of putting the wrong thing in $-[0] and $+[0],\nbut this usually can be worked around.\n\nHow do I match a regular expression that's in a variable?\n(contributed by brian d foy)\n\nWe don't have to hard-code patterns into the match operator (or anything\nelse that works with regular expressions). We can put the pattern in a\nvariable for later use.\n\nThe match operator is a double quote context, so you can interpolate\nyour variable just like a double quoted string. In this case, you read\nthe regular expression as user input and store it in $regex. Once you\nhave the pattern in $regex, you use that variable in the match operator.\n\nchomp( my $regex = <STDIN> );\n\nif( $string =~ m/$regex/ ) { ... }\n\nAny regular expression special characters in $regex are still special,\nand the pattern still has to be valid or Perl will complain. For\ninstance, in this pattern there is an unpaired parenthesis.\n\nmy $regex = \"Unmatched ( paren\";\n\n\"Two parens to bind them all\" =~ m/$regex/;\n\nWhen Perl compiles the regular expression, it treats the parenthesis as\nthe start of a memory match. When it doesn't find the closing\nparenthesis, it complains:\n\nUnmatched ( in regex; marked by <-- HERE in m/Unmatched ( <-- HERE  paren/ at script line 3.\n\nYou can get around this in several ways depending on our situation.\nFirst, if you don't want any of the characters in the string to be\nspecial, you can escape them with \"quotemeta\" before you use the string.\n\nchomp( my $regex = <STDIN> );\n$regex = quotemeta( $regex );\n\nif( $string =~ m/$regex/ ) { ... }\n\nYou can also do this directly in the match operator using the \"\\Q\" and\n\"\\E\" sequences. The \"\\Q\" tells Perl where to start escaping special\ncharacters, and the \"\\E\" tells it where to stop (see perlop for more\ndetails).\n\nchomp( my $regex = <STDIN> );\n\nif( $string =~ m/\\Q$regex\\E/ ) { ... }\n\nAlternately, you can use \"qr//\", the regular expression quote operator\n(see perlop for more details). It quotes and perhaps compiles the\npattern, and you can apply regular expression flags to the pattern.\n\nchomp( my $input = <STDIN> );\n\nmy $regex = qr/$input/is;\n\n$string =~ m/$regex/  # same as m/$input/is;\n\nYou might also want to trap any errors by wrapping an \"eval\" block\naround the whole thing.\n\nchomp( my $input = <STDIN> );\n\neval {\nif( $string =~ m/\\Q$input\\E/ ) { ... }\n};\nwarn $@ if $@;\n\nOr...\n\nmy $regex = eval { qr/$input/is };\nif( defined $regex ) {\n$string =~ m/$regex/;\n}\nelse {\nwarn $@;\n}\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq7.pod": {
            "content": "Can I get a BNF/yacc/RE for the Perl language?\nThere is no BNF, but you can paw your way through the yacc grammar in\nperly.y in the source distribution if you're particularly brave. The\ngrammar relies on very smart tokenizing code, so be prepared to venture\ninto toke.c as well.\n\nIn the words of Chaim Frenkel: \"Perl's grammar can not be reduced to\nBNF. The work of parsing perl is distributed between yacc, the lexer,\nsmoke and mirrors.\"\n\nWhat are all these $@%&* punctuation signs, and how do I know when to use them?\nThey are type specifiers, as detailed in perldata:\n\n$ for scalar values (number, string or reference)\n@ for arrays\n% for hashes (associative arrays)\n& for subroutines (aka functions, procedures, methods)\n* for all types of that symbol name. In version 4 you used them like\npointers, but in modern perls you can just use references.\n\nThere are a couple of other symbols that you're likely to encounter that\naren't really type specifiers:\n\n<> are used for inputting a record from a filehandle.\n\\  takes a reference to something.\n\nNote that <FILE> is *neither* the type specifier for files nor the name\nof the handle. It is the \"<>\" operator applied to the handle FILE. It\nreads one line (well, record--see \"$/\" in perlvar) from the handle FILE\nin scalar context, or *all* lines in list context. When performing open,\nclose, or any other operation besides \"<>\" on files, or even when\ntalking about the handle, do *not* use the brackets. These are correct:",
            "subsections": [
                {
                    "name": "eof",
                    "content": "Do I always/never have to quote my strings or use semicolons and commas?\nNormally, a bareword doesn't need to be quoted, but in most cases\nprobably should be (and must be under \"use strict\"). But a hash key\nconsisting of a simple word and the left-hand operand to the \"=>\"\noperator both count as though they were quoted:\n\nThis                    is like this\n------------            ---------------\n$foo{line}              $foo{'line'}\nbar => stuff            'bar' => stuff\n\nThe final semicolon in a block is optional, as is the final comma in a\nlist. Good style (see perlstyle) says to put them in except for\none-liners:\n\nif ($whoops) { exit 1 }\nmy @nums = (1, 2, 3);\n\nif ($whoops) {\nexit 1;\n}\n\nmy @lines = (\n\"There Beren came from mountains cold\",\n\"And lost he wandered under leaves\",\n);\n\nHow do I skip some return values?\nOne way is to treat the return values as a list and index into it:\n\n$dir = (getpwnam($user))[7];\n\nAnother way is to use undef as an element on the left-hand-side:\n\n($dev, $ino, undef, undef, $uid, $gid) = stat($file);\n\nYou can also use a list slice to select only the elements that you need:\n\n($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5];\n\nHow do I temporarily block warnings?\nIf you are running Perl 5.6.0 or better, the \"use warnings\" pragma\nallows fine control of what warnings are produced. See perllexwarn for\nmore details.\n\n{\nno warnings;          # temporarily turn off warnings\n$x = $y + $z;         # I know these might be undef\n}\n\nAdditionally, you can enable and disable categories of warnings. You\nturn off the categories you want to ignore and you can still get other\ncategories of warnings. See perllexwarn for the complete details,\nincluding the category names and hierarchy.\n\n{\nno warnings 'uninitialized';\n$x = $y + $z;\n}\n\nIf you have an older version of Perl, the $^W variable (documented in\nperlvar) controls runtime warnings for a block:\n\n{\nlocal $^W = 0;        # temporarily turn off warnings\n$x = $y + $z;         # I know these might be undef\n}\n\nNote that like all the punctuation variables, you cannot currently use"
                },
                {
                    "name": "my",
                    "content": "Why do Perl operators have different precedence than C operators?\nActually, they don't. All C operators that Perl copies have the same\nprecedence in Perl as they do in C. The problem is with operators that C\ndoesn't have, especially functions that give a list context to\neverything on their right, eg. print, chmod, exec, and so on. Such\nfunctions are called \"list operators\" and appear as such in the\nprecedence table in perlop.\n\nA common mistake is to write:\n\nunlink $file || die \"snafu\";\n\nThis gets interpreted as:\n\nunlink ($file || die \"snafu\");\n\nTo avoid this problem, either put in extra parentheses or use the super\nlow precedence \"or\" operator:\n\n(unlink $file) || die \"snafu\";\nunlink $file or die \"snafu\";\n\nThe \"English\" operators (\"and\", \"or\", \"xor\", and \"not\") deliberately\nhave precedence lower than that of list operators for just such\nsituations as the one above.\n\nAnother operator with surprising precedence is exponentiation. It binds\nmore tightly even than unary minus, making \"-22\" produce a negative\nfour and not a positive one. It is also right-associating, meaning that\n\"232\" is two raised to the ninth power, not eight squared.\n\nAlthough it has the same precedence as in C, Perl's \"?:\" operator\nproduces an lvalue. This assigns $x to either $iftrue or $iffalse,\ndepending on the trueness of $maybe:\n\n($maybe ? $iftrue : $iffalse) = $x;\n\nHow do I declare/create a structure?\nIn general, you don't \"declare\" a structure. Just use a (probably\nanonymous) hash reference. See perlref and perldsc for details. Here's\nan example:\n\n$person = {};                   # new anonymous hash\n$person->{AGE}  = 24;           # set field AGE to 24\n$person->{NAME} = \"Nat\";        # set field NAME to \"Nat\"\n\nIf you're looking for something a bit more rigorous, try perlootut.\n\nHow do I create a module?\nperlnewmod is a good place to start, ignore the bits about uploading to\nCPAN if you don't want to make your module publicly available.\n\nExtUtils::ModuleMaker and Module::Starter are also good places to start.\nMany CPAN authors now use Dist::Zilla to automate as much as possible.\n\nDetailed documentation about modules can be found at: perlmod,\nperlmodlib, perlmodstyle.\n\nIf you need to include C code or C library interfaces use h2xs. h2xs\nwill create the module distribution structure and the initial interface\nfiles. perlxs and perlxstut explain the details.\n\nHow do I adopt or take over a module already on CPAN?\nAsk the current maintainer to make you a co-maintainer or transfer the\nmodule to you.\n\nIf you can not reach the author for some reason contact the PAUSE admins\nat modules@perl.org who may be able to help, but each case is treated\nseparately.\n\n*   Get a login for the Perl Authors Upload Server (PAUSE) if you don't\nalready have one: <http://pause.perl.org>\n\n*   Write to modules@perl.org explaining what you did to contact the\ncurrent maintainer. The PAUSE admins will also try to reach the\nmaintainer.\n\n*   Post a public message in a heavily trafficked site announcing your\nintention to take over the module.\n\n*   Wait a bit. The PAUSE admins don't want to act too quickly in case\nthe current maintainer is on holiday. If there's no response to\nprivate communication or the public post, a PAUSE admin can transfer\nit to you.\n\nHow do I create a class?\n(contributed by brian d foy)\n\nIn Perl, a class is just a package, and methods are just subroutines.\nPerl doesn't get more formal than that and lets you set up the package\njust the way that you like it (that is, it doesn't set up anything for\nyou).\n\nSee also perlootut, a tutorial that covers class creation, and perlobj.\n\nHow can I tell if a variable is tainted?\nYou can use the tainted() function of the Scalar::Util module, available\nfrom CPAN (or included with Perl since release 5.8.0). See also\n\"Laundering and Detecting Tainted Data\" in perlsec.\n\nWhat's a closure?\nClosures are documented in perlref.\n\n*Closure* is a computer science term with a precise but hard-to-explain\nmeaning. Usually, closures are implemented in Perl as anonymous\nsubroutines with lasting references to lexical variables outside their\nown scopes. These lexicals magically refer to the variables that were\naround when the subroutine was defined (deep binding).\n\nClosures are most often used in programming languages where you can have\nthe return value of a function be itself a function, as you can in Perl.\nNote that some languages provide anonymous functions but are not capable\nof providing proper closures: the Python language, for example. For more\ninformation on closures, check out any textbook on functional\nprogramming. Scheme is a language that not only supports but encourages\nclosures.\n\nHere's a classic non-closure function-generating function:\n\nsub addfunctiongenerator {\nreturn sub { shift() + shift() };\n}\n\nmy $addsub = addfunctiongenerator();\nmy $sum = $addsub->(4,5);                # $sum is 9 now.\n\nThe anonymous subroutine returned by addfunctiongenerator() isn't\ntechnically a closure because it refers to no lexicals outside its own\nscope. Using a closure gives you a *function template* with some\ncustomization slots left out to be filled later.\n\nContrast this with the following makeadder() function, in which the\nreturned anonymous function contains a reference to a lexical variable\noutside the scope of that function itself. Such a reference requires\nthat Perl return a proper closure, thus locking in for all time the\nvalue that the lexical had when the function was created.\n\nsub makeadder {\nmy $addpiece = shift;\nreturn sub { shift() + $addpiece };\n}\n\nmy $f1 = makeadder(20);\nmy $f2 = makeadder(555);\n\nNow $f1->($n) is always 20 plus whatever $n you pass in, whereas\n$f2->($n) is always 555 plus whatever $n you pass in. The $addpiece in\nthe closure sticks around.\n\nClosures are often used for less esoteric purposes. For example, when\nyou want to pass in a bit of code into a function:\n\nmy $line;\ntimeout( 30, sub { $line = <STDIN> } );\n\nIf the code to execute had been passed in as a string, '$line =\n<STDIN>', there would have been no way for the hypothetical timeout()\nfunction to access the lexical variable $line back in its caller's\nscope.\n\nAnother use for a closure is to make a variable *private* to a named\nsubroutine, e.g. a counter that gets initialized at creation time of the\nsub and can only be modified from within the sub. This is sometimes used\nwith a BEGIN block in package files to make sure a variable doesn't get\nmeddled with during the lifetime of the package:\n\nBEGIN {\nmy $id = 0;\nsub nextid { ++$id }\n}\n\nThis is discussed in more detail in perlsub; see the entry on\n*Persistent Private Variables*.\n\nWhat is variable suicide and how can I prevent it?\nThis problem was fixed in perl 5.00405, so preventing it means\nupgrading your version of perl. ;)\n\nVariable suicide is when you (temporarily or permanently) lose the value\nof a variable. It is caused by scoping through my() and local()\ninteracting with either closures or aliased foreach() iterator variables\nand subroutine arguments. It used to be easy to inadvertently lose a\nvariable's value this way, but now it's much harder. Take this code:\n\nmy $f = 'foo';\nsub T {\nwhile ($i++ < 3) { my $f = $f; $f .= \"bar\"; print $f, \"\\n\" }\n}\n\nT;\nprint \"Finally $f\\n\";\n\nIf you are experiencing variable suicide, that \"my $f\" in the subroutine\ndoesn't pick up a fresh copy of the $f whose value is 'foo'. The output\nshows that inside the subroutine the value of $f leaks through when it\nshouldn't, as in this output:\n\nfoobar\nfoobarbar\nfoobarbarbar\nFinally foo\n\nThe $f that has \"bar\" added to it three times should be a new $f \"my $f\"\nshould create a new lexical variable each time through the loop. The\nexpected output is:\n\nfoobar\nfoobar\nfoobar\nFinally foo\n\nHow can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?\nYou need to pass references to these objects. See \"Pass by Reference\" in\nperlsub for this particular question, and perlref for information on\nreferences.\n\nPassing Variables and Functions\nRegular variables and functions are quite easy to pass: just pass in\na reference to an existing or anonymous variable or function:\n\nfunc( \\$somescalar );\n\nfunc( \\@somearray  );\nfunc( [ 1 .. 10 ]   );\n\nfunc( \\%somehash   );\nfunc( { this => 10, that => 20 }   );\n\nfunc( \\&somefunc   );\nfunc( sub { $[0]  $[1] }   );\n\nPassing Filehandles\nAs of Perl 5.6, you can represent filehandles with scalar variables\nwhich you treat as any other scalar.\n\nopen my $fh, $filename or die \"Cannot open $filename! $!\";\nfunc( $fh );\n\nsub func {\nmy $passedfh = shift;\n\nmy $line = <$passedfh>;\n}\n\nBefore Perl 5.6, you had to use the *FH or \"\\*FH\" notations. These\nare \"typeglobs\"--see \"Typeglobs and Filehandles\" in perldata and\nespecially \"Pass by Reference\" in perlsub for more information.\n\nPassing Regexes\nHere's an example of how to pass in a string and a regular\nexpression for it to match against. You construct the pattern with\nthe \"qr//\" operator:\n\nsub compare {\nmy ($val1, $regex) = @;\nmy $retval = $val1 =~ /$regex/;\nreturn $retval;\n}\n$match = compare(\"old McDonald\", qr/d.*D/i);\n\nPassing Methods\nTo pass an object method into a subroutine, you can do this:\n\ncallalot(10, $someobj, \"methname\")\nsub callalot {\nmy ($count, $widget, $trick) = @;\nfor (my $i = 0; $i < $count; $i++) {\n$widget->$trick();\n}\n}\n\nOr, you can use a closure to bundle up the object, its method call,\nand arguments:\n\nmy $whatnot = sub { $someobj->obfuscate(@args) };\nfunc($whatnot);\nsub func {\nmy $code = shift;\n&$code();\n}\n\nYou could also investigate the can() method in the UNIVERSAL class\n(part of the standard perl distribution).\n\nHow do I create a static variable?\n(contributed by brian d foy)\n\nIn Perl 5.10, declare the variable with \"state\". The \"state\" declaration\ncreates the lexical variable that persists between calls to the\nsubroutine:\n\nsub counter { state $count = 1; $count++ }\n\nYou can fake a static variable by using a lexical variable which goes\nout of scope. In this example, you define the subroutine \"counter\", and\nit uses the lexical variable $count. Since you wrap this in a BEGIN\nblock, $count is defined at compile-time, but also goes out of scope at\nthe end of the BEGIN block. The BEGIN block also ensures that the\nsubroutine and the value it uses is defined at compile-time so the\nsubroutine is ready to use just like any other subroutine, and you can\nput this code in the same place as other subroutines in the program text\n(i.e. at the end of the code, typically). The subroutine \"counter\" still\nhas a reference to the data, and is the only way you can access the\nvalue (and each time you do, you increment the value). The data in chunk\nof memory defined by $count is private to \"counter\".\n\nBEGIN {\nmy $count = 1;\nsub counter { $count++ }\n}\n\nmy $start = counter();\n\n.... # code that calls counter();\n\nmy $end = counter();\n\nIn the previous example, you created a function-private variable because\nonly one function remembered its reference. You could define multiple\nfunctions while the variable is in scope, and each function can share\nthe \"private\" variable. It's not really \"static\" because you can access\nit outside the function while the lexical variable is in scope, and even\ncreate references to it. In this example, \"incrementcount\" and\n\"returncount\" share the variable. One function adds to the value and\nthe other simply returns the value. They can both access $count, and\nsince it has gone out of scope, there is no other way to access it.\n\nBEGIN {\nmy $count = 1;\nsub incrementcount { $count++ }\nsub returncount    { $count }\n}\n\nTo declare a file-private variable, you still use a lexical variable. A\nfile is also a scope, so a lexical variable defined in the file cannot\nbe seen from any other file.\n\nSee \"Persistent Private Variables\" in perlsub for more information. The\ndiscussion of closures in perlref may help you even though we did not\nuse anonymous subroutines in this answer. See \"Persistent Private\nVariables\" in perlsub for details.\n\nWhat's the difference between dynamic and lexical (static) scoping? Between local() and my()?"
                },
                {
                    "name": "local",
                    "content": "a new value for the duration of the subroutine *which is visible in\nother functions called from that subroutine*. This is done at run-time,\nso is called dynamic scoping. local() always affects global variables,\nalso called package variables or dynamic variables.\n"
                },
                {
                    "name": "my",
                    "content": "subroutine. This is done at compile-time, so it is called lexical or\nstatic scoping. my() always affects private variables, also called\nlexical variables or (improperly) static(ly scoped) variables.\n\nFor instance:\n\nsub visible {\nprint \"var has value $var\\n\";\n}\n\nsub dynamic {\nlocal $var = 'local';    # new temporary value for the still-global\nvisible();              #   variable called $var\n}\n\nsub lexical {\nmy $var = 'private';    # new private variable, $var\nvisible();              # (invisible outside of sub scope)\n}\n\n$var = 'global';\n\nvisible();              # prints global\ndynamic();              # prints local\nlexical();              # prints global\n\nNotice how at no point does the value \"private\" get printed. That's\nbecause $var only has that value within the block of the lexical()\nfunction, and it is hidden from the called subroutine.\n\nIn summary, local() doesn't make what you think of as private, local\nvariables. It gives a global variable a temporary value. my() is what\nyou're looking for if you want private variables.\n\nSee \"Private Variables via my()\" in perlsub and \"Temporary Values via"
                },
                {
                    "name": "local",
                    "content": "How can I access a dynamic variable while a similarly named lexical is in scope?\nIf you know your package, you can just mention it explicitly, as in\n$SomePack::var. Note that the notation $::var is not the dynamic $var\nin the current package, but rather the one in the \"main\" package, as\nthough you had written $main::var.\n\nuse vars '$var';\nlocal $var = \"global\";\nmy    $var = \"lexical\";\n\nprint \"lexical is $var\\n\";\nprint \"global  is $main::var\\n\";\n\nAlternatively you can use the compiler directive our() to bring a\ndynamic variable into the current lexical scope.\n\nrequire 5.006; # our() did not exist before 5.6\nuse vars '$var';\n\nlocal $var = \"global\";\nmy $var    = \"lexical\";\n\nprint \"lexical is $var\\n\";\n\n{\nour $var;\nprint \"global  is $var\\n\";\n}\n\nWhat's the difference between deep and shallow binding?\nIn deep binding, lexical variables mentioned in anonymous subroutines\nare the same ones that were in scope when the subroutine was created. In\nshallow binding, they are whichever variables with the same names happen\nto be in scope when the subroutine is called. Perl always uses deep\nbinding of lexical variables (i.e., those created with my()). However,\ndynamic variables (aka global, local, or package variables) are\neffectively shallowly bound. Consider this just one more reason not to\nuse them. See the answer to \"What's a closure?\".\n\nWhy doesn't \"my($foo) = <$fh>;\" work right?"
                },
                {
                    "name": "my",
                    "content": "<$fh> read operation, like so many of Perl's functions and operators,\ncan tell which context it was called in and behaves appropriately. In\ngeneral, the scalar() function can help. This function does nothing to\nthe data itself (contrary to popular myth) but rather tells its argument\nto behave in whatever its scalar fashion is. If that function doesn't\nhave a defined scalar behavior, this of course doesn't help you (such as\nwith sort()).\n\nTo enforce scalar context in this particular case, however, you need\nmerely omit the parentheses:\n\nlocal($foo) = <$fh>;        # WRONG\nlocal($foo) = scalar(<$fh>);   # ok\nlocal $foo  = <$fh>;        # right\n\nYou should probably be using lexical variables anyway, although the\nissue is the same here:\n\nmy($foo) = <$fh>;    # WRONG\nmy $foo  = <$fh>;    # right\n\nHow do I redefine a builtin function, operator, or method?\nWhy do you want to do that? :-)\n\nIf you want to override a predefined function, such as open(), then\nyou'll have to import the new definition from a different module. See\n\"Overriding Built-in Functions\" in perlsub.\n\nIf you want to overload a Perl operator, such as \"+\" or \"\", then\nyou'll want to use the \"use overload\" pragma, documented in overload.\n\nIf you're talking about obscuring method calls in parent classes, see\n\"Overriding methods and method resolution\" in perlootut.\n\nWhat's the difference between calling a function as &foo and foo()?\n(contributed by brian d foy)\n\nCalling a subroutine as &foo with no trailing parentheses ignores the\nprototype of \"foo\" and passes it the current value of the argument list,\n@. Here's an example; the \"bar\" subroutine calls &foo, which prints its\narguments list:\n\nsub foo { print \"Args in foo are: @\\n\"; }\n\nsub bar { &foo; }\n\nbar( \"a\", \"b\", \"c\" );\n\nWhen you call \"bar\" with arguments, you see that \"foo\" got the same @:\n\nArgs in foo are: a b c\n\nCalling the subroutine with trailing parentheses, with or without\narguments, does not use the current @. Changing the example to put\nparentheses after the call to \"foo\" changes the program:\n\nsub foo { print \"Args in foo are: @\\n\"; }\n\nsub bar { &foo(); }\n\nbar( \"a\", \"b\", \"c\" );\n\nNow the output shows that \"foo\" doesn't get the @ from its caller.\n\nArgs in foo are:\n\nHowever, using \"&\" in the call still overrides the prototype of \"foo\" if\npresent:\n\nsub foo ($$$) { print \"Args infoo are: @\\n\"; }\n\nsub bar1 { &foo; }\nsub bar2 { &foo(); }\nsub bar3 { foo( $[0], $[1], $[2] ); }\n# sub bar4 { foo(); }\n# bar4 doesn't compile: \"Not enough arguments for main::foo at ...\"\n\nbar1( \"a\", \"b\", \"c\" );\n# Args in foo are: a b c\n\nbar2( \"a\", \"b\", \"c\" );\n# Args in foo are:\n\nbar3( \"a\", \"b\", \"c\" );\n# Args in foo are: a b c\n\nThe main use of the @ pass-through feature is to write subroutines\nwhose main job it is to call other subroutines for you. For further\ndetails, see perlsub.\n\nHow can I catch accesses to undefined variables, functions, or methods?\nThe AUTOLOAD method, discussed in \"Autoloading\" in perlsub lets you\ncapture calls to undefined functions and methods.\n\nWhen it comes to undefined variables that would trigger a warning under\n\"use warnings\", you can promote the warning to an error.\n\nuse warnings FATAL => qw(uninitialized);\n\nWhy can't a method included in this same file be found?\nSome possible reasons: your inheritance is getting confused, you've\nmisspelled the method name, or the object is of the wrong type. Check\nout perlootut for details about any of the above cases. You may also use\n\"print ref($object)\" to find out the class $object was blessed into.\n\nAnother possible reason for problems is that you've used the indirect\nobject syntax (eg, \"find Guru \"Samy\"\") on a class name before Perl has\nseen that such a package exists. It's wisest to make sure your packages\nare all defined before you start using them, which will be taken care of\nif you use the \"use\" statement instead of \"require\". If not, make sure\nto use arrow notation (eg., \"Guru->find(\"Samy\")\") instead. Object\nnotation is explained in perlobj.\n\nMake sure to read about creating modules in perlmod and the perils of\nindirect objects in \"Method Invocation\" in perlobj.\n\nHow can I find out my current or calling package?\n(contributed by brian d foy)\n\nTo find the package you are currently in, use the special literal\n\"PACKAGE\", as documented in perldata. You can only use the special\nliterals as separate tokens, so you can't interpolate them into strings\nlike you can with variables:\n\nmy $currentpackage = PACKAGE;\nprint \"I am in package $currentpackage\\n\";\n\nIf you want to find the package calling your code, perhaps to give\nbetter diagnostics as Carp does, use the \"caller\" built-in:\n\nsub foo {\nmy @args = ...;\nmy( $package, $filename, $line ) = caller;\n\nprint \"I was called from package $package\\n\";\n);\n\nBy default, your program starts in package \"main\", so you will always be\nin some package.\n\nThis is different from finding out the package an object is blessed\ninto, which might not be the current package. For that, use \"blessed\"\nfrom Scalar::Util, part of the Standard Library since Perl 5.8:\n\nuse Scalar::Util qw(blessed);\nmy $objectpackage = blessed( $object );\n\nMost of the time, you shouldn't care what package an object is blessed\ninto, however, as long as it claims to inherit from that class:\n\nmy $isrightclass = eval { $object->isa( $package ) }; # true or false\n\nAnd, with Perl 5.10 and later, you don't have to check for an\ninheritance to see if the object can handle a role. For that, you can\nuse \"DOES\", which comes from \"UNIVERSAL\":\n\nmy $classdoesit = eval { $object->DOES( $role ) }; # true or false\n\nYou can safely replace \"isa\" with \"DOES\" (although the converse is not\ntrue).\n\nHow can I comment out a large block of Perl code?\n(contributed by brian d foy)\n\nThe quick-and-dirty way to comment out more than one line of Perl is to\nsurround those lines with Pod directives. You have to put these\ndirectives at the beginning of the line and somewhere where Perl expects\na new statement (so not in the middle of statements like the \"#\"\ncomments). You end the comment with \"=cut\", ending the Pod section:\n\n=pod\n\nmy $object = NotGonnaHappen->new();\n\nignoredsub();\n\n$wontbeassigned = 37;\n\n=cut\n\nThe quick-and-dirty method only works well when you don't plan to leave\nthe commented code in the source. If a Pod parser comes along, your\nmultiline comment is going to show up in the Pod translation. A better\nway hides it from Pod parsers as well.\n\nThe \"=begin\" directive can mark a section for a particular purpose. If\nthe Pod parser doesn't want to handle it, it just ignores it. Label the\ncomments with \"comment\". End the comment using \"=end\" with the same\nlabel. You still need the \"=cut\" to go back to Perl code from the Pod\ncomment:\n\n=begin comment\n\nmy $object = NotGonnaHappen->new();\n\nignoredsub();\n\n$wontbeassigned = 37;\n\n=end comment\n\n=cut\n\nFor more information on Pod, check out perlpod and perlpodspec.\n\nHow do I clear a package?\nUse this code, provided by Mark-Jason Dominus:\n\nsub scrubpackage {\nno strict 'refs';\nmy $pack = shift;\ndie \"Shouldn't delete main package\"\nif $pack eq \"\" || $pack eq \"main\";\nmy $stash = *{$pack . '::'}{HASH};\nmy $name;\nforeach $name (keys %$stash) {\nmy $fullname = $pack . '::' . $name;\n# Get rid of everything with that name.\nundef $$fullname;\nundef @$fullname;\nundef %$fullname;\nundef &$fullname;\nundef *$fullname;\n}\n}\n\nOr, if you're using a recent release of Perl, you can just use the\nSymbol::deletepackage() function instead.\n\nHow can I use a variable as a variable name?\nBeginners often think they want to have a variable contain the name of a\nvariable.\n\n$fred    = 23;\n$varname = \"fred\";\n++$$varname;         # $fred now 24\n\nThis works *sometimes*, but it is a very bad idea for two reasons.\n\nThe first reason is that this technique *only works on global\nvariables*. That means that if $fred is a lexical variable created with"
                },
                {
                    "name": "my",
                    "content": "accidentally access the global and skip right over the private lexical\naltogether. Global variables are bad because they can easily collide\naccidentally and in general make for non-scalable and confusing code.\n\nSymbolic references are forbidden under the \"use strict\" pragma. They\nare not true references and consequently are not reference-counted or\ngarbage-collected.\n\nThe other reason why using a variable to hold the name of another\nvariable is a bad idea is that the question often stems from a lack of\nunderstanding of Perl data structures, particularly hashes. By using\nsymbolic references, you are just using the package's symbol-table hash\n(like %main::) instead of a user-defined hash. The solution is to use\nyour own hash or a real reference instead.\n\n$USERVARS{\"fred\"} = 23;\nmy $varname = \"fred\";\n$USERVARS{$varname}++;  # not $$varname++\n\nThere we're using the %USERVARS hash instead of symbolic references.\nSometimes this comes up in reading strings from the user with variable\nreferences and wanting to expand them to the values of your perl\nprogram's variables. This is also a bad idea because it conflates the\nprogram-addressable namespace and the user-addressable one. Instead of\nreading a string and expanding it to the actual contents of your\nprogram's own variables:\n\n$str = 'this has a $fred and $barney in it';\n$str =~ s/(\\$\\w+)/$1/eeg;          # need double eval\n\nit would be better to keep a hash around like %USERVARS and have\nvariable references actually refer to entries in that hash:\n\n$str =~ s/\\$(\\w+)/$USERVARS{$1}/g;   # no /e here at all\n\nThat's faster, cleaner, and safer than the previous approach. Of course,\nyou don't need to use a dollar sign. You could use your own scheme to\nmake it less confusing, like bracketed percent symbols, etc.\n\n$str = 'this has a %fred% and %barney% in it';\n$str =~ s/%(\\w+)%/$USERVARS{$1}/g;   # no /e here at all\n\nAnother reason that folks sometimes think they want a variable to\ncontain the name of a variable is that they don't know how to build\nproper data structures using hashes. For example, let's say they wanted\ntwo hashes in their program: %fred and %barney, and that they wanted to\nuse another scalar variable to refer to those by name.\n\n$name = \"fred\";\n$$name{WIFE} = \"wilma\";     # set %fred\n\n$name = \"barney\";\n$$name{WIFE} = \"betty\";    # set %barney\n\nThis is still a symbolic reference, and is still saddled with the\nproblems enumerated above. It would be far better to write:\n\n$folks{\"fred\"}{WIFE}   = \"wilma\";\n$folks{\"barney\"}{WIFE} = \"betty\";\n\nAnd just use a multilevel hash to start with.\n\nThe only times that you absolutely *must* use symbolic references are\nwhen you really must refer to the symbol table. This may be because it's\nsomething that one can't take a real reference to, such as a format\nname. Doing so may also be important for method calls, since these\nalways go through the symbol table for resolution.\n\nIn those cases, you would turn off \"strict 'refs'\" temporarily so you\ncan play around with the symbol table. For example:\n\n@colors = qw(red blue green yellow orange purple violet);\nfor my $name (@colors) {\nno strict 'refs';  # renege for the block\n*$name = sub { \"<FONT COLOR='$name'>@</FONT>\" };\n}\n\nAll those functions (red(), blue(), green(), etc.) appear to be\nseparate, but the real code in the closure actually was compiled only\nonce.\n\nSo, sometimes you might want to use symbolic references to manipulate\nthe symbol table directly. This doesn't matter for formats, handles, and\nsubroutines, because they are always global--you can't use my() on them.\nFor scalars, arrays, and hashes, though--and usually for subroutines--\nyou probably only want to use hard references.\n\nDo I need to recompile XS modules when there is a change in the C library?\n(contributed by Alex Beamish)\n\nIf the new version of the C library is ABI-compatible (that's\nApplication Binary Interface compatible) with the version you're\nupgrading from, and if the shared library version didn't change, no\nre-compilation should be necessary.\n"
                }
            ]
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq8.pod": {
            "content": "How do I print something out in color?\nIn general, you don't, because you don't know whether the recipient has\na color-aware display device. If you know that they have an ANSI\nterminal that understands color, you can use the Term::ANSIColor module\nfrom CPAN:\n\nuse Term::ANSIColor;\nprint color(\"red\"), \"Stop!\\n\", color(\"reset\");\nprint color(\"green\"), \"Go!\\n\", color(\"reset\");\n\nOr like this:\n\nuse Term::ANSIColor qw(:constants);\nprint RED, \"Stop!\\n\", RESET;\nprint GREEN, \"Go!\\n\", RESET;\n\nHow do I clear the screen?\n(contributed by brian d foy)\n\nTo clear the screen, you just have to print the special sequence that\ntells the terminal to clear the screen. Once you have that sequence,\noutput it when you want to clear the screen.\n\nYou can use the Term::ANSIScreen module to get the special sequence.\nImport the \"cls\" function (or the \":screen\" tag):\n\nuse Term::ANSIScreen qw(cls);\nmy $clearscreen = cls();\n\nprint $clearscreen;\n\nThe Term::Cap module can also get the special sequence if you want to\ndeal with the low-level details of terminal control. The \"Tputs\" method\nreturns the string for the given capability:\n\nuse Term::Cap;\n\nmy $terminal = Term::Cap->Tgetent( { OSPEED => 9600 } );\nmy $clearscreen = $terminal->Tputs('cl');\n\nprint $clearscreen;\n\nOn Windows, you can use the Win32::Console module. After creating an\nobject for the output filehandle you want to affect, call the \"Cls\"\nmethod:\n\nWin32::Console;\n\nmy $OUT = Win32::Console->new(STDOUTPUTHANDLE);\nmy $clearstring = $OUT->Cls;\n\nprint $clearscreen;\n\nIf you have a command-line program that does the job, you can call it in\nbackticks to capture whatever it outputs so you can use it later:\n\nmy $clearstring = `clear`;\n\nprint $clearstring;\n\nHow do I read and write the serial port?\nThis depends on which operating system your program is running on. In\nthe case of Unix, the serial ports will be accessible through files in\n\"/dev\"; on other systems, device names will doubtless differ. Several\nproblem areas common to all device interaction are the following:\n\nlockfiles\nYour system may use lockfiles to control multiple access. Make sure\nyou follow the correct protocol. Unpredictable behavior can result\nfrom multiple processes reading from one device.\n\nopen mode\nIf you expect to use both read and write operations on the device,\nyou'll have to open it for update (see \"open\" in perlfunc for\ndetails). You may wish to open it without running the risk of\nblocking by using sysopen() and \"ORDWR|ONDELAY|ONOCTTY\" from the\nFcntl module (part of the standard perl distribution). See \"sysopen\"\nin perlfunc for more on this approach.\n\nend of line\nSome devices will be expecting a \"\\r\" at the end of each line rather\nthan a \"\\n\". In some ports of perl, \"\\r\" and \"\\n\" are different from\ntheir usual (Unix) ASCII values of \"\\015\" and \"\\012\". You may have\nto give the numeric values you want directly, using octal (\"\\015\"),\nhex (\"0x0D\"), or as a control-character specification (\"\\cM\").\n\nprint DEV \"atv1\\012\";    # wrong, for some devices\nprint DEV \"atv1\\015\";    # right, for some devices\n\nEven though with normal text files a \"\\n\" will do the trick, there\nis still no unified scheme for terminating a line that is portable\nbetween Unix, DOS/Win, and Macintosh, except to terminate *ALL* line\nends with \"\\015\\012\", and strip what you don't need from the output.\nThis applies especially to socket I/O and autoflushing, discussed\nnext.\n\nflushing output\nIf you expect characters to get to your device when you print()\nthem, you'll want to autoflush that filehandle. You can use select()\nand the $| variable to control autoflushing (see \"$|\" in perlvar and\n\"select\" in perlfunc, or perlfaq5, \"How do I flush/unbuffer an\noutput filehandle? Why must I do this?\"):\n\nmy $oldhandle = select($devfh);\n$| = 1;\nselect($oldhandle);\n\nYou'll also see code that does this without a temporary variable, as\nin\n\nselect((select($debhandle), $| = 1)[0]);\n\nOr if you don't mind pulling in a few thousand lines of code just\nbecause you're afraid of a little $| variable:\n\nuse IO::Handle;\n$devfh->autoflush(1);\n\nAs mentioned in the previous item, this still doesn't work when\nusing socket I/O between Unix and Macintosh. You'll need to hard\ncode your line terminators, in that case.\n\nnon-blocking input\nIf you are doing a blocking read() or sysread(), you'll have to\narrange for an alarm handler to provide a timeout (see \"alarm\" in\nperlfunc). If you have a non-blocking open, you'll likely have a\nnon-blocking read, which means you may have to use a 4-arg select()\nto determine whether I/O is ready on that device (see \"select\" in\nperlfunc.\n\nWhile trying to read from his caller-id box, the notorious Jamie\nZawinski \"<jwz@netscape.com>\", after much gnashing of teeth and fighting\nwith \"sysread\", \"sysopen\", POSIX's \"tcgetattr\" business, and various\nother functions that go bump in the night, finally came up with this:\n\nsub openmodem {\nuse IPC::Open2;\nmy $stty = `/bin/stty -g`;\nopen2( \\*MODEMIN, \\*MODEMOUT, \"cu -l$modemdevice -s2400 2>&1\");\n# starting cu hoses /dev/tty's stty settings, even when it has\n# been opened on a pipe...\nsystem(\"/bin/stty $stty\");\n$ = <MODEMIN>;\nchomp;\nif ( !m/^Connected/ ) {\nprint STDERR \"$0: cu printed `$' instead of `Connected'\\n\";\n}\n}\n\nHow do I decode encrypted password files?\nYou spend lots and lots of money on dedicated hardware, but this is\nbound to get you talked about.\n\nSeriously, you can't if they are Unix password files--the Unix password\nsystem employs one-way encryption. It's more like hashing than\nencryption. The best you can do is check whether something else hashes\nto the same string. You can't turn a hash back into the original string.\nPrograms like Crack can forcibly (and intelligently) try to guess\npasswords, but don't (can't) guarantee quick success.\n\nIf you're worried about users selecting bad passwords, you should\nproactively check when they try to change their password (by modifying",
            "subsections": [
                {
                    "name": "passwd",
                    "content": "How do I trap control characters/signals?\nYou don't actually \"trap\" a control character. Instead, that character\ngenerates a signal which is sent to your terminal's currently\nforegrounded process group, which you then trap in your process. Signals\nare documented in \"Signals\" in perlipc and the section on \"Signals\" in\nthe Camel.\n\nYou can set the values of the %SIG hash to be the functions you want to\nhandle the signal. After perl catches the signal, it looks in %SIG for a\nkey with the same name as the signal, then calls the subroutine value\nfor that key.\n\n# as an anonymous subroutine\n\n$SIG{INT} = sub { syswrite(STDERR, \"ouch\\n\", 5 ) };\n\n# or a reference to a function\n\n$SIG{INT} = \\&ouch;\n\n# or the name of the function as a string\n\n$SIG{INT} = \"ouch\";\n\nPerl versions before 5.8 had in its C source code signal handlers which\nwould catch the signal and possibly run a Perl function that you had set\nin %SIG. This violated the rules of signal handling at that level\ncausing perl to dump core. Since version 5.8.0, perl looks at %SIG after\nthe signal has been caught, rather than while it is being caught.\nPrevious versions of this answer were incorrect.\n\nHow do I modify the shadow password file on a Unix system?\nIf perl was installed correctly and your shadow library was written\nproperly, the \"getpw*()\" functions described in perlfunc should in\ntheory provide (read-only) access to entries in the shadow password\nfile. To change the file, make a new shadow password file (the format\nvaries from system to system--see passwd(1) for specifics) and use"
                },
                {
                    "name": "pwd_mkdb",
                    "content": "How can I sleep() or alarm() for under a second?\nIf you want finer granularity than the 1 second that the sleep()\nfunction provides, the easiest way is to use the select() function as\ndocumented in \"select\" in perlfunc. Try the Time::HiRes and the\nBSD::Itimer modules (available from CPAN, and starting from Perl 5.8\nTime::HiRes is part of the standard distribution).\n\nHow can I do an atexit() or setjmp()/longjmp()? (Exception handling)\nYou can use the \"END\" block to simulate atexit(). Each package's \"END\"\nblock is called when the program or thread ends. See the perlmod manpage\nfor more details about \"END\" blocks.\n\nFor example, you can use this to make sure your filter program managed\nto finish its output without filling up the disk:\n\nEND {\nclose(STDOUT) || die \"stdout close failed: $!\";\n}\n\nThe \"END\" block isn't called when untrapped signals kill the program,\nthough, so if you use \"END\" blocks you should also use\n\nuse sigtrap qw(die normal-signals);\n\nPerl's exception-handling mechanism is its eval() operator. You can use"
                },
                {
                    "name": "eval",
                    "content": "section on signals, especially the time-out handler for a blocking"
                },
                {
                    "name": "flock",
                    "content": "*Programming Perl*.\n\nIf exception handling is all you're interested in, use one of the many\nCPAN modules that handle exceptions, such as Try::Tiny.\n\nIf you want the atexit() syntax (and an rmexit() as well), try the\n\"AtExit\" module available from CPAN.\n\nWhy doesn't my sockets program work under System V (Solaris)? What does the error message \"Protocol not supported\" mean?\nSome Sys-V based systems, notably Solaris 2.X, redefined some of the\nstandard socket constants. Since these were constant across all\narchitectures, they were often hardwired into perl code. The proper way\nto deal with this is to \"use Socket\" to get the correct values.\n\nNote that even though SunOS and Solaris are binary compatible, these\nvalues are different. Go figure.\n\nHow can I call my system's unique C functions from Perl?\nIn most cases, you write an external module to do it--see the answer to\n\"Where can I learn about linking C with Perl? [h2xs, xsubpp]\". However,\nif the function is a system call, and your system supports syscall(),\nyou can use the \"syscall\" function (documented in perlfunc).\n\nRemember to check the modules that came with your distribution, and CPAN\nas well--someone may already have written a module to do it. On Windows,\ntry Win32::API. On Macs, try Mac::Carbon. If no module has an interface\nto the C function, you can inline a bit of C in your Perl source with\nInline::C.\n\nWhere do I get the include files to do ioctl() or syscall()?\nHistorically, these would be generated by the h2ph tool, part of the\nstandard perl distribution. This program converts cpp(1) directives in C\nheader files to files containing subroutine definitions, like\nSYSgetitimer(), which you can use as arguments to your functions. It\ndoesn't work perfectly, but it usually gets most of the job done. Simple\nfiles like errno.h, syscall.h, and socket.h were fine, but the hard ones\nlike ioctl.h nearly always need to be hand-edited. Here's how to install\nthe *.ph files:\n\n1. Become the super-user\n2. cd /usr/include\n3. h2ph *.h */*.h\n\nIf your system supports dynamic loading, for reasons of portability and\nsanity you probably ought to use h2xs (also part of the standard perl\ndistribution). This tool converts C header files to Perl extensions. See\nperlxstut for how to get started with h2xs.\n\nIf your system doesn't support dynamic loading, you still probably ought\nto use h2xs. See perlxstut and ExtUtils::MakeMaker for more information\n(in brief, just use make perl instead of a plain make to rebuild perl\nwith a new static extension).\n\nWhy do setuid perl scripts complain about kernel problems?\nSome operating systems have bugs in the kernel that make setuid scripts\ninherently insecure. Perl gives you a number of options (described in\nperlsec) to work around such systems.\n\nHow can I capture STDERR from an external command?\nThere are three basic ways of running external commands:\n\nsystem $cmd;        # using system()\nmy $output = `$cmd`;        # using backticks (``)\nopen (my $pipefh, \"$cmd |\");    # using open()\n\nWith system(), both STDOUT and STDERR will go the same place as the\nscript's STDOUT and STDERR, unless the system() command redirects them.\nBackticks and open() read only the STDOUT of your command.\n\nYou can also use the open3() function from IPC::Open3. Benjamin Goldberg\nprovides some sample code:\n\nTo capture a program's STDOUT, but discard its STDERR:\n\nuse IPC::Open3;\nuse File::Spec;\nmy $in = '';\nopen(NULL, \">\", File::Spec->devnull);\nmy $pid = open3($in, \\*PH, \">&NULL\", \"cmd\");\nwhile( <PH> ) { }\nwaitpid($pid, 0);\n\nTo capture a program's STDERR, but discard its STDOUT:\n\nuse IPC::Open3;\nuse File::Spec;\nmy $in = '';\nopen(NULL, \">\", File::Spec->devnull);\nmy $pid = open3($in, \">&NULL\", \\*PH, \"cmd\");\nwhile( <PH> ) { }\nwaitpid($pid, 0);\n\nTo capture a program's STDERR, and let its STDOUT go to our own STDERR:\n\nuse IPC::Open3;\nmy $in = '';\nmy $pid = open3($in, \">&STDERR\", \\*PH, \"cmd\");\nwhile( <PH> ) { }\nwaitpid($pid, 0);\n\nTo read both a command's STDOUT and its STDERR separately, you can\nredirect them to temp files, let the command run, then read the temp\nfiles:\n\nuse IPC::Open3;\nuse IO::File;\nmy $in = '';\nlocal *CATCHOUT = IO::File->newtmpfile;\nlocal *CATCHERR = IO::File->newtmpfile;\nmy $pid = open3($in, \">&CATCHOUT\", \">&CATCHERR\", \"cmd\");\nwaitpid($pid, 0);\nseek $, 0, 0 for \\*CATCHOUT, \\*CATCHERR;\nwhile( <CATCHOUT> ) {}\nwhile( <CATCHERR> ) {}\n\nBut there's no real need for both to be tempfiles... the following\nshould work just as well, without deadlocking:\n\nuse IPC::Open3;\nmy $in = '';\nuse IO::File;\nlocal *CATCHERR = IO::File->newtmpfile;\nmy $pid = open3($in, \\*CATCHOUT, \">&CATCHERR\", \"cmd\");\nwhile( <CATCHOUT> ) {}\nwaitpid($pid, 0);\nseek CATCHERR, 0, 0;\nwhile( <CATCHERR> ) {}\n\nAnd it'll be faster, too, since we can begin processing the program's\nstdout immediately, rather than waiting for the program to finish.\n\nWith any of these, you can change file descriptors before the call:\n\nopen(STDOUT, \">logfile\");\nsystem(\"ls\");\n\nor you can use Bourne shell file-descriptor redirection:\n\n$output = `$cmd 2>somefile`;\nopen (PIPE, \"cmd 2>somefile |\");\n\nYou can also use file-descriptor redirection to make STDERR a duplicate\nof STDOUT:\n\n$output = `$cmd 2>&1`;\nopen (PIPE, \"cmd 2>&1 |\");\n\nNote that you *cannot* simply open STDERR to be a dup of STDOUT in your\nPerl program and avoid calling the shell to do the redirection. This\ndoesn't work:\n\nopen(STDERR, \">&STDOUT\");\n$alloutput = `cmd args`;  # stderr still escapes\n\nThis fails because the open() makes STDERR go to where STDOUT was going\nat the time of the open(). The backticks then make STDOUT go to a\nstring, but don't change STDERR (which still goes to the old STDOUT).\n\nNote that you *must* use Bourne shell (sh(1)) redirection syntax in\nbackticks, not csh(1)! Details on why Perl's system() and backtick and\npipe opens all use the Bourne shell are in the versus/csh.whynot article\nin the \"Far More Than You Ever Wanted To Know\" collection in\n<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> . To capture a command's\nSTDERR and STDOUT together:\n\n$output = `cmd 2>&1`;                       # either with backticks\n$pid = open(PH, \"cmd 2>&1 |\");              # or with an open pipe\nwhile (<PH>) { }                            #    plus a read\n\nTo capture a command's STDOUT but discard its STDERR:\n\n$output = `cmd 2>/dev/null`;                # either with backticks\n$pid = open(PH, \"cmd 2>/dev/null |\");       # or with an open pipe\nwhile (<PH>) { }                            #    plus a read\n\nTo capture a command's STDERR but discard its STDOUT:\n\n$output = `cmd 2>&1 1>/dev/null`;           # either with backticks\n$pid = open(PH, \"cmd 2>&1 1>/dev/null |\");  # or with an open pipe\nwhile (<PH>) { }                            #    plus a read\n\nTo exchange a command's STDOUT and STDERR in order to capture the STDERR\nbut leave its STDOUT to come out our old STDERR:\n\n$output = `cmd 3>&1 1>&2 2>&3 3>&-`;        # either with backticks\n$pid = open(PH, \"cmd 3>&1 1>&2 2>&3 3>&-|\");# or with an open pipe\nwhile (<PH>) { }                            #    plus a read\n\nTo read both a command's STDOUT and its STDERR separately, it's easiest\nto redirect them separately to files, and then read from those files\nwhen the program is done:\n\nsystem(\"program args 1>program.stdout 2>program.stderr\");\n\nOrdering is important in all these examples. That's because the shell\nprocesses file descriptor redirections in strictly left to right order.\n\nsystem(\"prog args 1>tmpfile 2>&1\");\nsystem(\"prog args 2>&1 1>tmpfile\");\n\nThe first command sends both standard out and standard error to the\ntemporary file. The second command sends only the old standard output\nthere, and the old standard error shows up on the old standard out.\n\nWhy doesn't open() return an error when a pipe open fails?\nIf the second argument to a piped open() contains shell metacharacters,\nperl fork()s, then exec()s a shell to decode the metacharacters and\neventually run the desired program. If the program couldn't be run, it's\nthe shell that gets the message, not Perl. All your Perl program can\nfind out is whether the shell itself could be successfully started. You\ncan still capture the shell's STDERR and check it for error messages.\nSee \"How can I capture STDERR from an external command?\" elsewhere in\nthis document, or use the IPC::Open3 module.\n\nIf there are no shell metacharacters in the argument of open(), Perl\nruns the command directly, without using the shell, and can correctly\nreport whether the command started.\n\nHow can I call backticks without shell processing?\nThis is a bit tricky. You can't simply write the command like this:\n\n@ok = `grep @opts '$searchstring' @filenames`;\n\nAs of Perl 5.8.0, you can use open() with multiple arguments. Just like\nthe list forms of system() and exec(), no shell escapes happen.\n\nopen( GREP, \"-|\", 'grep', @opts, $searchstring, @filenames );\nchomp(@ok = <GREP>);\nclose GREP;\n\nYou can also:\n\nmy @ok = ();\nif (open(GREP, \"-|\")) {\nwhile (<GREP>) {\nchomp;\npush(@ok, $);\n}\nclose GREP;\n} else {\nexec 'grep', @opts, $searchstring, @filenames;\n}\n\nJust as with system(), no shell escapes happen when you exec() a list.\nFurther examples of this can be found in \"Safe Pipe Opens\" in perlipc.\n\nNote that if you're using Windows, no solution to this vexing issue is\neven possible. Even though Perl emulates fork(), you'll still be stuck,\nbecause Windows does not have an argc/argv-style API.\n\nHow can I convert my shell script to perl?\nLearn Perl and rewrite it. Seriously, there's no simple converter.\nThings that are awkward to do in the shell are easy to do in Perl, and\nthis very awkwardness is what would make a shell->perl converter nigh-on\nimpossible to write. By rewriting it, you'll think about what you're\nreally trying to do, and hopefully will escape the shell's pipeline\ndatastream paradigm, which while convenient for some matters, causes\nmany inefficiencies.\n\nCan I use perl to run a telnet or ftp session?\nTry the Net::FTP, TCP::Client, and Net::Telnet modules (available from\nCPAN). <http://www.cpan.org/scripts/netstuff/telnet.emul.shar> will also\nhelp for emulating the telnet protocol, but Net::Telnet is quite\nprobably easier to use.\n\nIf all you want to do is pretend to be telnet but don't need the initial\ntelnet handshaking, then the standard dual-process approach will\nsuffice:\n\nuse IO::Socket;             # new in 5.004\nmy $handle = IO::Socket::INET->new('www.perl.com:80')\nor die \"can't connect to port 80 on www.perl.com $!\";\n$handle->autoflush(1);\nif (fork()) {               # XXX: undef means failure\nselect($handle);\nprint while <STDIN>;    # everything from stdin to socket\n} else {\nprint while <$handle>;  # everything from socket to stdout\n}\nclose $handle;\nexit;\n\nHow can I write expect in Perl?\nOnce upon a time, there was a library called chat2.pl (part of the\nstandard perl distribution), which never really got finished. If you\nfind it somewhere, *don't use it*. These days, your best bet is to look\nat the Expect module available from CPAN, which also requires two other\nmodules from CPAN, IO::Pty and IO::Stty.\n\nIs there a way to hide perl's command line from programs such as \"ps\"?\nFirst of all note that if you're doing this for security reasons (to\navoid people seeing passwords, for example) then you should rewrite your\nprogram so that critical information is never given as an argument.\nHiding the arguments won't make your program completely secure.\n\nTo actually alter the visible command line, you can assign to the\nvariable $0 as documented in perlvar. This won't work on all operating\nsystems, though. Daemon programs like sendmail place their state there,\nas in:\n\n$0 = \"orcus [accepting connections]\";\n\nI {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?\nUnix\nIn the strictest sense, it can't be done--the script executes as a\ndifferent process from the shell it was started from. Changes to a\nprocess are not reflected in its parent--only in any children\ncreated after the change. There is shell magic that may allow you to\nfake it by eval()ing the script's output in your shell; check out\nthe comp.unix.questions FAQ for details.\n\nHow do I close a process's filehandle without waiting for it to complete?\nAssuming your system supports such things, just send an appropriate\nsignal to the process (see \"kill\" in perlfunc). It's common to first\nsend a TERM signal, wait a little bit, and then send a KILL signal to\nfinish it off.\n\nHow do I find out if I'm running interactively or not?\n(contributed by brian d foy)\n\nThis is a difficult question to answer, and the best answer is only a\nguess.\n\nWhat do you really want to know? If you merely want to know if one of\nyour filehandles is connected to a terminal, you can try the \"-t\" file\ntest:\n\nif( -t STDOUT ) {\nprint \"I'm connected to a terminal!\\n\";\n}\n\nHowever, you might be out of luck if you expect that means there is a\nreal person on the other side. With the Expect module, another program\ncan pretend to be a person. The program might even come close to passing\nthe Turing test.\n\nThe IO::Interactive module does the best it can to give you an answer.\nIts \"isinteractive\" function returns an output filehandle; that\nfilehandle points to standard output if the module thinks the session is\ninteractive. Otherwise, the filehandle is a null handle that simply\ndiscards the output:\n\nuse IO::Interactive;\n\nprint { isinteractive } \"I might go to standard output!\\n\";\n\nThis still doesn't guarantee that a real person is answering your\nprompts or reading your output.\n\nIf you want to know how to handle automated testing for your\ndistribution, you can check the environment. The CPAN Testers, for\ninstance, set the value of \"AUTOMATEDTESTING\":\n\nunless( $ENV{AUTOMATEDTESTING} ) {\nprint \"Hello interactive tester!\\n\";\n}\n\nHow do I timeout a slow event?\nUse the alarm() function, probably in conjunction with a signal handler,\nas documented in \"Signals\" in perlipc and the section on \"Signals\" in\nthe Camel. You may instead use the more flexible Sys::AlarmCall module\navailable from CPAN.\n\nThe alarm() function is not implemented on all versions of Windows.\nCheck the documentation for your specific version of Perl.\n\nHow do I set CPU limits?\n(contributed by Xho)\n\nUse the BSD::Resource module from CPAN. As an example:\n\nuse BSD::Resource;\nsetrlimit(RLIMITCPU,10,20) or die $!;\n\nThis sets the soft and hard limits to 10 and 20 seconds, respectively.\nAfter 10 seconds of time spent running on the CPU (not \"wall\" time), the\nprocess will be sent a signal (XCPU on some systems) which, if not\ntrapped, will cause the process to terminate. If that signal is trapped,\nthen after 10 more seconds (20 seconds in total) the process will be\nkilled with a non-trappable signal.\n\nSee the BSD::Resource and your systems documentation for the gory\ndetails.\n\nHow do I use an SQL database?\nThe DBI module provides an abstract interface to most database servers\nand types, including Oracle, DB2, Sybase, mysql, Postgresql, ODBC, and\nflat files. The DBI module accesses each database type through a\ndatabase driver, or DBD. You can see a complete list of available\ndrivers on CPAN: <http://www.cpan.org/modules/by-module/DBD/> . You can\nread more about DBI on <http://dbi.perl.org/> .\n\nOther modules provide more specific access: Win32::ODBC, Alzabo,\n\"iodbc\", and others found on CPAN Search: <https://metacpan.org/> .\n\nHow do I make a system() exit on control-C?\nYou can't. You need to imitate the system() call (see perlipc for sample\ncode) and then have a signal handler for the INT signal that passes the\nsignal on to the subprocess. Or you can check for it:\n\n$rc = system($cmd);\nif ($rc & 127) { die \"signal death\" }\n\nHow do I open a file without blocking?\nIf you're lucky enough to be using a system that supports non-blocking\nreads (most Unixish systems do), you need only to use the \"ONDELAY\" or\n\"ONONBLOCK\" flag from the \"Fcntl\" module in conjunction with sysopen():\n\nuse Fcntl;\nsysopen(my $fh, \"/foo/somefile\", OWRONLY|ONDELAY|OCREAT, 0644)\nor die \"can't open /foo/somefile: $!\":\n\nHow do I tell the difference between errors from the shell and perl?\n(answer contributed by brian d foy)\n\nWhen you run a Perl script, something else is running the script for\nyou, and that something else may output error messages. The script might\nemit its own warnings and error messages. Most of the time you cannot\ntell who said what.\n\nYou probably cannot fix the thing that runs perl, but you can change how\nperl outputs its warnings by defining a custom warning and die\nfunctions.\n\nConsider this script, which has an error you may not notice immediately.\n\n#!/usr/locl/bin/perl\n\nprint \"Hello World\\n\";\n\nI get an error when I run this from my shell (which happens to be bash).\nThat may look like perl forgot it has a print() function, but my shebang\nline is not the path to perl, so the shell runs the script, and I get\nthe error.\n\n$ ./test\n./test: line 3: print: command not found\n\nA quick and dirty fix involves a little bit of code, but this may be all\nyou need to figure out the problem.\n\n#!/usr/bin/perl -w\n\nBEGIN {\n$SIG{WARN} = sub{ print STDERR \"Perl: \", @; };\n$SIG{DIE}  = sub{ print STDERR \"Perl: \", @; exit 1};\n}\n\n$a = 1 + undef;\n$x / 0;\nEND\n\nThe perl message comes out with \"Perl\" in front. The \"BEGIN\" block works\nat compile time so all of the compilation errors and warnings get the\n\"Perl:\" prefix too.\n\nPerl: Useless use of division (/) in void context at ./test line 9.\nPerl: Name \"main::a\" used only once: possible typo at ./test line 8.\nPerl: Name \"main::x\" used only once: possible typo at ./test line 9.\nPerl: Use of uninitialized value in addition (+) at ./test line 8.\nPerl: Use of uninitialized value in division (/) at ./test line 9.\nPerl: Illegal division by zero at ./test line 9.\nPerl: Illegal division by zero at -e line 3.\n\nIf I don't see that \"Perl:\", it's not from perl.\n\nYou could also just know all the perl errors, and although there are\nsome people who may know all of them, you probably don't. However, they\nall should be in the perldiag manpage. If you don't find the error in\nthere, it probably isn't a perl error.\n\nLooking up every message is not the easiest way, so let perl to do it\nfor you. Use the diagnostics pragma with turns perl's normal messages\ninto longer discussions on the topic.\n\nuse diagnostics;\n\nIf you don't get a paragraph or two of expanded discussion, it might not\nbe perl's message.\n\nHow do I install a module from CPAN?\n(contributed by brian d foy)\n\nThe easiest way is to have a module also named CPAN do it for you by\nusing the \"cpan\" command that comes with Perl. You can give it a list of\nmodules to install:\n\n$ cpan IO::Interactive Getopt::Whatever\n\nIf you prefer \"CPANPLUS\", it's just as easy:\n\n$ cpanp i IO::Interactive Getopt::Whatever\n\nIf you want to install a distribution from the current directory, you\ncan tell \"CPAN.pm\" to install \".\" (the full stop):\n\n$ cpan .\n\nSee the documentation for either of those commands to see what else you\ncan do.\n\nIf you want to try to install a distribution by yourself, resolving all\ndependencies on your own, you follow one of two possible build paths.\n\nFor distributions that use *Makefile.PL*:\n\n$ perl Makefile.PL\n$ make test install\n\nFor distributions that use *Build.PL*:\n\n$ perl Build.PL\n$ ./Build test\n$ ./Build install\n\nSome distributions may need to link to libraries or other third-party\ncode and their build and installation sequences may be more complicated.\nCheck any *README* or *INSTALL* files that you may find.\n\nHow do I keep my own module/library directory?\nWhen you build modules, tell Perl where to install the modules.\n\nIf you want to install modules for your own use, the easiest way might\nbe local::lib, which you can download from CPAN. It sets various\ninstallation settings for you, and uses those same settings within your\nprograms.\n\nIf you want more flexibility, you need to configure your CPAN client for\nyour particular situation.\n\nFor \"Makefile.PL\"-based distributions, use the INSTALLBASE option when\ngenerating Makefiles:\n\nperl Makefile.PL INSTALLBASE=/mydir/perl\n\nYou can set this in your \"CPAN.pm\" configuration so modules\nautomatically install in your private library directory when you use the\nCPAN.pm shell:\n\n% cpan\ncpan> o conf makeplarg INSTALLBASE=/mydir/perl\ncpan> o conf commit\n\nFor \"Build.PL\"-based distributions, use the --installbase option:\n\nperl Build.PL --installbase /mydir/perl\n\nYou can configure \"CPAN.pm\" to automatically use this option too:\n\n% cpan\ncpan> o conf mbuildarg \"--installbase /mydir/perl\"\ncpan> o conf commit\n\nINSTALLBASE tells these tools to put your modules into\n/mydir/perl/lib/perl5. See \"How do I add a directory to my include path\n(@INC) at runtime?\" for details on how to run your newly installed\nmodules.\n\nThere is one caveat with INSTALLBASE, though, since it acts differently\nfrom the PREFIX and LIB settings that older versions of\nExtUtils::MakeMaker advocated. INSTALLBASE does not support installing\nmodules for multiple versions of Perl or different architectures under\nthe same directory. You should consider whether you really want that\nand, if you do, use the older PREFIX and LIB settings. See the\nExtUtils::Makemaker documentation for more details.\n\nHow do I add the directory my program lives in to the module/library search path?\n(contributed by brian d foy)\n\nIf you know the directory already, you can add it to @INC as you would\nfor any other directory. You might \"use lib\" if you know the directory\nat compile time:\n\nuse lib $directory;\n\nThe trick in this task is to find the directory. Before your script does\nanything else (such as a \"chdir\"), you can get the current working\ndirectory with the \"Cwd\" module, which comes with Perl:\n\nBEGIN {\nuse Cwd;\nour $directory = cwd;\n}\n\nuse lib $directory;\n\nYou can do a similar thing with the value of $0, which holds the script\nname. That might hold a relative path, but \"rel2abs\" can turn it into an\nabsolute path. Once you have the\n\nBEGIN {\nuse File::Spec::Functions qw(rel2abs);\nuse File::Basename qw(dirname);\n\nmy $path   = rel2abs( $0 );\nour $directory = dirname( $path );\n}\n\nuse lib $directory;\n\nThe FindBin module, which comes with Perl, might work. It finds the\ndirectory of the currently running script and puts it in $Bin, which you\ncan then use to construct the right library path:\n\nuse FindBin qw($Bin);\n\nYou can also use local::lib to do much of the same thing. Install\nmodules using local::lib's settings then use the module in your program:\n\nuse local::lib; # sets up a local lib at ~/perl5\n\nSee the local::lib documentation for more details.\n\nHow do I add a directory to my include path (@INC) at runtime?\nHere are the suggested ways of modifying your include path, including\nenvironment variables, run-time switches, and in-code statements:\n\nthe \"PERLLIB\" environment variable\n$ export PERLLIB=/path/to/my/dir\n$ perl program.pl\n\nthe \"PERL5LIB\" environment variable\n$ export PERL5LIB=/path/to/my/dir\n$ perl program.pl\n\nthe \"perl -Idir\" command line flag\n$ perl -I/path/to/my/dir program.pl\n\nthe \"lib\" pragma:\nuse lib \"$ENV{HOME}/myownperllib\";\n\nthe local::lib module:\nuse local::lib;\n\nuse local::lib \"~/myownperllib\";\n\nWhere are modules installed?\nModules are installed on a case-by-case basis (as provided by the\nmethods described in the previous section), and in the operating system.\nAll of these paths are stored in @INC, which you can display with the\none-liner\n\nperl -e 'print join(\"\\n\",@INC,\"\")'\n\nThe same information is displayed at the end of the output from the\ncommand\n\nperl -V\n\nTo find out where a module's source code is located, use\n\nperldoc -l Encode\n\nto display the path to the module. In some cases (for example, the\n\"AutoLoader\" module), this command will show the path to a separate\n\"pod\" file; the module itself should be in the same directory, with a\n'pm' file extension.\n"
                }
            ]
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq9.pod": {
            "content": "Should I use a web framework?\nYes. If you are building a web site with any level of interactivity\n(forms / users / databases), you will want to use a framework to make\nhandling requests and responses easier.\n\nIf there is no interactivity then you may still want to look at using\nsomething like Template Toolkit <https://metacpan.org/module/Template>\nor Plack::Middleware::TemplateToolkit so maintenance of your HTML files\n(and other assets) is easier.\n\nWhich web framework should I use?\nThere is no simple answer to this question. Perl frameworks can run\neverything from basic file servers and small scale intranets to massive\nmultinational multilingual websites that are the core to international\nbusinesses.\n\nBelow is a list of a few frameworks with comments which might help you\nin making a decision, depending on your specific requirements. Start by\nreading the docs, then ask questions on the relevant mailing list or IRC\nchannel.\n\nCatalyst\nStrongly object-oriented and fully-featured with a long development\nhistory and a large community and addon ecosystem. It is excellent\nfor large and complex applications, where you have full control over\nthe server.\n\nDancer2\nFree of legacy weight, providing a lightweight and easy to learn\nAPI. Has a growing addon ecosystem. It is best used for smaller\nprojects and very easy to learn for beginners.\n\nMojolicious\nSelf-contained and powerful for both small and larger projects, with\na focus on HTML5 and real-time web technologies such as WebSockets.\n\nWeb::Simple\nStrongly object-oriented and minimal, built for speed and intended\nas a toolkit for building micro web apps, custom frameworks or for\ntieing together existing Plack-compatible web applications with one\ncentral dispatcher.\n\nAll of these interact with or use Plack which is worth understanding the\nbasics of when building a website in Perl (there is a lot of useful\nPlack::Middleware\n<https://metacpan.org/search?q=plack%3A%3Amiddleware>).\n\nWhat is Plack and PSGI?\nPSGI is the Perl Web Server Gateway Interface Specification, it is a\nstandard that many Perl web frameworks use, you should not need to\nunderstand it to build a web site, the part you might want to use is\nPlack.\n\nPlack is a set of tools for using the PSGI stack. It contains middleware\n<https://metacpan.org/search?q=plack%3A%3Amiddleware> components, a\nreference server and utilities for Web application frameworks. Plack is\nlike Ruby's Rack or Python's Paste for WSGI.\n\nYou could build a web site using Plack and your own code, but for\nanything other than a very basic web site, using a web framework (that\nuses <https://plackperl.org>) is a better option.\n\nHow do I remove HTML from a string?\nUse HTML::Strip, or HTML::FormatText which not only removes HTML but\nalso attempts to do a little simple formatting of the resulting plain\ntext.\n\nHow do I extract URLs?\nHTML::SimpleLinkExtor will extract URLs from HTML, it handles anchors,\nimages, objects, frames, and many other tags that can contain a URL. If\nyou need anything more complex, you can create your own subclass of\nHTML::LinkExtor or HTML::Parser. You might even use\nHTML::SimpleLinkExtor as an example for something specifically suited to\nyour needs.\n\nYou can use URI::Find or URL::Search to extract URLs from an arbitrary\ntext document.\n\nHow do I fetch an HTML file?\n(contributed by brian d foy)\n\nThe core HTTP::Tiny module can fetch web resources and give their\ncontent back to you as a string:\n\nuse HTTP::Tiny;\n\nmy $ua = HTTP::Tiny->new;\nmy $html = $ua->get( \"http://www.example.com/index.html\" )->{content};\n\nIt can also store the resource directly in a file:\n\n$ua->mirror( \"http://www.example.com/index.html\", \"foo.html\" );\n\nIf you need to do something more complicated, the HTTP::Tiny object can\nbe customized by setting attributes, or you can use LWP::UserAgent from\nthe libwww-perl distribution or Mojo::UserAgent from the Mojolicious\ndistribution to make common tasks easier. If you want to simulate an\ninteractive web browser, you can use the WWW::Mechanize module.\n\nHow do I automate an HTML form submission?\nIf you are doing something complex, such as moving through many pages\nand forms or a web site, you can use WWW::Mechanize. See its\ndocumentation for all the details.\n\nIf you're submitting values using the GET method, create a URL and\nencode the form using the \"wwwformurlencode\" method from HTTP::Tiny:\n\nuse HTTP::Tiny;\n\nmy $ua = HTTP::Tiny->new;\n\nmy $query = $ua->wwwformurlencode([ q => 'DBFile', lucky => 1 ]);\nmy $url = \"https://metacpan.org/search?$query\";\nmy $content = $ua->get($url)->{content};\n\nIf you're using the POST method, the \"postform\" method will encode the\ncontent appropriately.\n\nuse HTTP::Tiny;\n\nmy $ua = HTTP::Tiny->new;\n\nmy $url = 'https://metacpan.org/search';\nmy $form = [ q => 'DBFile', lucky => 1 ];\nmy $content = $ua->postform($url, $form)->{content};\n\nHow do I make sure users can't enter values into a form that causes my CGI script to do bad things?\n(contributed by brian d foy)\n\nYou can't prevent people from sending your script bad data. Even if you\nadd some client-side checks, people may disable them or bypass them\ncompletely. For instance, someone might use a module such as LWP to\nsubmit to your web site. If you want to prevent data that try to use SQL\ninjection or other sorts of attacks (and you should want to), you have\nto not trust any data that enter your program.\n\nThe perlsec documentation has general advice about data security. If you\nare using the DBI module, use placeholder to fill in data. If you are\nrunning external programs with \"system\" or \"exec\", use the list forms.\nThere are many other precautions that you should take, too many to list\nhere, and most of them fall under the category of not using any data\nthat you don't intend to use. Trust no one.\n\nHow do I parse a mail header?\nUse the Email::MIME module. It's well-tested and supports all the\ncraziness that you'll see in the real world (comment-folding whitespace,\nencodings, comments, etc.).\n\nuse Email::MIME;\n\nmy $message = Email::MIME->new($rfc2822);\nmy $subject = $message->header('Subject');\nmy $from    = $message->header('From');\n\nIf you've already got some other kind of email object, consider passing\nit to Email::Abstract and then using its cast method to get an\nEmail::MIME object:\n\nmy $abstract = Email::Abstract->new($mailmessageobject);\nmy $emailmimeobject = $abstract->cast('Email::MIME');\n\nHow do I check a valid mail address?\n(partly contributed by Aaron Sherman)\n\nThis isn't as simple a question as it sounds. There are two parts:\n\na) How do I verify that an email address is correctly formatted?\n\nb) How do I verify that an email address targets a valid recipient?\n\nWithout sending mail to the address and seeing whether there's a human\non the other end to answer you, you cannot fully answer part *b*, but\nthe Email::Valid module will do both part *a* and part *b* as far as you\ncan in real-time.\n\nOur best advice for verifying a person's mail address is to have them\nenter their address twice, just as you normally do to change a password.\nThis usually weeds out typos. If both versions match, send mail to that\naddress with a personal message. If you get the message back and they've\nfollowed your directions, you can be reasonably assured that it's real.\n\nA related strategy that's less open to forgery is to give them a PIN\n(personal ID number). Record the address and PIN (best that it be a\nrandom one) for later processing. In the mail you send, include a link\nto your site with the PIN included. If the mail bounces, you know it's\nnot valid. If they don't click on the link, either they forged the\naddress or (assuming they got the message) following through wasn't\nimportant so you don't need to worry about it.\n\nHow do I find the user's mail address?\nAsk them for it. There are so many email providers available that it's\nunlikely the local system has any idea how to determine a user's email\naddress.\n\nThe exception is for organization-specific email (e.g.\nfoo@yourcompany.com) where policy can be codified in your program. In\nthat case, you could look at $ENV{USER}, $ENV{LOGNAME}, and getpwuid($<)\nin scalar context, like so:\n\nmy $username = getpwuid($<)\n\nBut you still cannot make assumptions about whether this is correct,\nunless your policy says it is. You really are best off asking the user.\n\nHow do I send email?\nUse the Email::Stuffer module, like so:\n\n# first, create your message\nmy $message = Email::Stuffer->from('you@example.com')\n->to('friend@example.com')\n->subject('Happy birthday!')\n->textbody(\"Happy birthday to you!\\n\");\n\n$message->sendordie;\n\nBy default, Email::Sender::Simple (the \"send\" and \"sendordie\" methods\nuse this under the hood) will try \"sendmail\" first, if it exists in your\n$PATH. This generally isn't the case. If there's a remote mail server\nyou use to send mail, consider investigating one of the Transport\nclasses. At time of writing, the available transports include:\n\nEmail::Sender::Transport::Sendmail\nThis is the default. If you can use the mail(1) or mailx(1) program\nto send mail from the machine where your code runs, you should be\nable to use this.\n\nEmail::Sender::Transport::SMTP\nThis transport contacts a remote SMTP server over TCP. It optionally\nuses TLS or SSL and can authenticate to the server via SASL.\n\nTelling Email::Stuffer to use your transport is straightforward.\n\n$message->transport($emailsendertransportobject)->sendordie;\n\nHow do I use MIME to make an attachment to a mail message?\nEmail::MIME directly supports multipart messages. Email::MIME objects\nthemselves are parts and can be attached to other Email::MIME objects.\nConsult the Email::MIME documentation for more information, including\nall of the supported methods and examples of their use.\n\nEmail::Stuffer uses Email::MIME under the hood to construct messages,\nand wraps the most common attachment tasks with the simple \"attach\" and\n\"attachfile\" methods.\n\nEmail::Stuffer->to('friend@example.com')\n->subject('The file')\n->attachfile('stuff.csv')\n->sendordie;\n\nHow do I read email?\nUse the Email::Folder module, like so:\n\nuse Email::Folder;\n\nmy $folder = Email::Folder->new('/path/to/email/folder');\nwhile(my $message = $folder->nextmessage) {\n# nextmessage returns Email::Simple objects, but we want\n# Email::MIME objects as they're more robust\nmy $mime = Email::MIME->new($message->asstring);\n}\n\nThere are different classes in the Email::Folder namespace for\nsupporting various mailbox types. Note that these modules are generally\nrather limited and only support reading rather than writing.\n\nHow do I fetch/put an (S)FTP file?\nNet::FTP, and Net::SFTP allow you to interact with FTP and SFTP (Secure\nFTP) servers.\n\nHow can I do RPC in Perl?\nUse one of the RPC modules( <https://metacpan.org/search?q=RPC> ).\n",
            "subsections": []
        }
    },
    "flags": [],
    "examples": [],
    "see_also": []
}