{
    "content": [
        {
            "type": "text",
            "text": "# F (perldoc)\n\n## Sections\n\n- **Found in /usr/share/perl/5.38/pod/perlfaq1.pod**\n- **Found in /usr/share/perl/5.38/pod/perlfaq2.pod**\n- **Found in /usr/share/perl/5.38/pod/perlfaq3.pod** (1 subsections)\n- **Found in /usr/share/perl/5.38/pod/perlfaq4.pod** (1 subsections)\n- **Found in /usr/share/perl/5.38/pod/perlfaq5.pod** (5 subsections)\n- **Found in /usr/share/perl/5.38/pod/perlfaq6.pod**\n- **Found in /usr/share/perl/5.38/pod/perlfaq7.pod** (4 subsections)\n- **Found in /usr/share/perl/5.38/pod/perlfaq8.pod** (2 subsections)\n- **Found in /usr/share/perl/5.38/pod/perlfaq9.pod**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "F",
        "section": "-q",
        "mode": "perldoc",
        "summary": null,
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "Found in /usr/share/perl/5.38/pod/perlfaq1.pod",
                "lines": 124,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.38/pod/perlfaq2.pod",
                "lines": 80,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.38/pod/perlfaq3.pod",
                "lines": 215,
                "subsections": [
                    {
                        "name": "mmap",
                        "lines": 114
                    }
                ]
            },
            {
                "name": "Found in /usr/share/perl/5.38/pod/perlfaq4.pod",
                "lines": 29,
                "subsections": [
                    {
                        "name": "ceil",
                        "lines": 1414
                    }
                ]
            },
            {
                "name": "Found in /usr/share/perl/5.38/pod/perlfaq5.pod",
                "lines": 726,
                "subsections": [
                    {
                        "name": "rename",
                        "lines": 4
                    },
                    {
                        "name": "flock",
                        "lines": 133
                    },
                    {
                        "name": "localtime",
                        "lines": 35
                    },
                    {
                        "name": "touch",
                        "lines": 4
                    },
                    {
                        "name": "utime",
                        "lines": 375
                    }
                ]
            },
            {
                "name": "Found in /usr/share/perl/5.38/pod/perlfaq6.pod",
                "lines": 305,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.38/pod/perlfaq7.pod",
                "lines": 126,
                "subsections": [
                    {
                        "name": "local",
                        "lines": 5
                    },
                    {
                        "name": "my",
                        "lines": 35
                    },
                    {
                        "name": "local",
                        "lines": 11
                    },
                    {
                        "name": "my",
                        "lines": 205
                    }
                ]
            },
            {
                "name": "Found in /usr/share/perl/5.38/pod/perlfaq8.pod",
                "lines": 138,
                "subsections": [
                    {
                        "name": "passwd",
                        "lines": 6
                    },
                    {
                        "name": "pwd_mkdb",
                        "lines": 506
                    }
                ]
            },
            {
                "name": "Found in /usr/share/perl/5.38/pod/perlfaq9.pod",
                "lines": 172,
                "subsections": []
            }
        ],
        "sections": {
            "Found in /usr/share/perl/5.38/pod/perlfaq1.pod": {
                "content": "Who 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\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\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",
                "subsections": []
            },
            "Found in /usr/share/perl/5.38/pod/perlfaq2.pod": {
                "content": "How can I get a binary version of Perl?\nSee CPAN Ports <http://www.cpan.org/ports/>\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 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",
                "subsections": []
            },
            "Found in /usr/share/perl/5.38/pod/perlfaq3.pod": {
                "content": "How 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 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\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 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\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 free an array or hash so my program shrinks?\n(contributed by Michael Carman)\n\nYou usually can't. Memory allocated to lexicals (i.e. my() variables)\ncannot be reclaimed or reused even if they go out of scope. It is\nreserved in case the variables come back into scope. Memory allocated to\nglobal variables can be reused (within your program) by using undef()\nand/or delete().\n\nOn most operating systems, memory allocated to a program can never be\nreturned to the system. That's why long-running programs sometimes re-\nexec themselves. Some operating systems (notably, systems that use",
                "subsections": [
                    {
                        "name": "mmap",
                        "content": "is no longer used, but on such systems, perl must be configured and\ncompiled to use the OS's malloc, not perl's.\n\nIn general, memory allocation and de-allocation isn't something you can\nor should be worrying about much in Perl.\n\nSee also \"How can I make my Perl program take less memory?\"\n\nHow can I make my CGI script more efficient?\nBeyond the normal measures described to make general Perl programs\nfaster or smaller, a CGI program has additional issues. It may be run\nseveral times per second. Given that each time it runs it will need to\nbe re-compiled and will often allocate a megabyte or more of system\nmemory, this can be a killer. Compiling into C isn't going to help you\nbecause the process start-up overhead is where the bottleneck is.\n\nThere are three popular ways to avoid this overhead. One solution\ninvolves running the Apache HTTP server (available from\n<http://www.apache.org/> ) with either of the modperl or modfastcgi\nplugin modules.\n\nWith modperl and the Apache::Registry module (distributed with\nmodperl), httpd will run with an embedded Perl interpreter which\npre-compiles your script and then executes it within the same address\nspace without forking. The Apache extension also gives Perl access to\nthe internal server API, so modules written in Perl can do just about\nanything a module written in C can. For more on modperl, see\n<http://perl.apache.org/>\n\nWith the FCGI module (from CPAN) and the modfastcgi module (available\nfrom <http://www.fastcgi.com/> ) each of your Perl programs becomes a\npermanent CGI daemon process.\n\nFinally, Plack is a Perl module and toolkit that contains PSGI\nmiddleware, helpers and adapters to web servers, allowing you to easily\ndeploy scripts which can continue running, and provides flexibility with\nregards to which web server you use. It can allow existing CGI scripts\nto enjoy this flexibility and performance with minimal changes, or can\nbe used along with modern Perl web frameworks to make writing and\ndeploying web services with Perl a breeze.\n\nThese solutions can have far-reaching effects on your system and on the\nway you write your CGI programs, so investigate them with care.\n\nSee also\n<http://www.cpan.org/modules/by-category/15WorldWideWebHTMLHTTPCGI\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\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"
                    }
                ]
            },
            "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\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 perform an operation on a series of integers?\nTo call a function on each element in an array, and collect the results,\nuse:\n\nmy @results = map { myfunc($) } @array;\n\nFor example:\n\nmy @triple = map { 3 * $ } @single;\n\nTo call a function on each element of an array, but ignore the results:\n\nforeach my $iterator (@array) {\nsomefunc($iterator);\n}\n\nTo call a function on each integer in a (small) range, you can use:\n\nmy @results = map { somefunc($) } (5 .. 25);\n\nbut you should be aware that in this form, the \"..\" operator creates a\nlist of all integers in the range, which can take a lot of memory for\nlarge ranges. However, the problem does not occur when using \"..\" within\na \"for\" loop, because in that case the range operator is optimized to\n*iterate* over the range, without creating the entire list. So\n\nmy @results = ();\nfor my $i (5 .. 500005) {\npush(@results, somefunc($i));\n}\n\nor even\n\npush(@results, somefunc($)) for 5 .. 500005;\n\nwill not create an intermediate list of 500,000 integers.\n\nHow do I find the day or week of the year?\nThe day of the year is in the list returned by the \"localtime\" function.\nWithout an argument \"localtime\" uses the current time.\n\nmy $dayofyear = (localtime)[7];\n\nThe POSIX module can also format a date as the day of the year or week\nof the year.\n\nuse POSIX qw/strftime/;\nmy $dayofyear  = strftime \"%j\", localtime;\nmy $weekofyear = strftime \"%W\", localtime;\n\nTo get the day of year for any date, use POSIX's \"mktime\" to get a time\nin epoch seconds for the argument to \"localtime\".\n\nuse POSIX qw/mktime strftime/;\nmy $weekofyear = strftime \"%W\",\nlocaltime( mktime( 0, 0, 0, 18, 11, 87 ) );\n\nYou can also use Time::Piece, which comes with Perl and provides a\n\"localtime\" that returns an object:\n\nuse Time::Piece;\nmy $dayofyear  = localtime->yday;\nmy $weekofyear = localtime->week;\n\nThe Date::Calc module provides two functions to calculate these, too:\n\nuse Date::Calc;\nmy $dayofyear  = DayofYear(  1987, 12, 18 );\nmy $weekofyear = WeekofYear( 1987, 12, 18 );\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 compare two dates and find the difference?\n(contributed by brian d foy)\n\nYou could just store all your dates as a number and then subtract. Life\nisn't always that simple though.\n\nThe Time::Piece module, which comes with Perl, replaces localtime with a\nversion that returns an object. It also overloads the comparison\noperators so you can compare them directly:\n\nuse Time::Piece;\nmy $date1 = localtime( $sometime );\nmy $date2 = localtime( $someothertime );\n\nif( $date1 < $date2 ) {\nprint \"The date was in the past\\n\";\n}\n\nYou can also get differences with a subtraction, which returns a\nTime::Seconds object:\n\nmy $datediff = $date1 - $date2;\nprint \"The difference is \", $datediff->days, \" days\\n\";\n\nIf you want to work with formatted dates, the Date::Manip, Date::Calc,\nor DateTime modules can help you.\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\nHow do I find yesterday's date?\n(contributed by brian d foy)\n\nTo do it correctly, you can use one of the \"Date\" modules since they\nwork with calendars instead of times. The DateTime module makes it\nsimple, and give you the same time of day, only the day before, despite\ndaylight saving time changes:\n\nuse DateTime;\n\nmy $yesterday = DateTime->now->subtract( days => 1 );\n\nprint \"Yesterday was $yesterday\\n\";\n\nYou can also use the Date::Calc module using its \"TodayandNow\"\nfunction.\n\nuse Date::Calc qw( TodayandNow AddDeltaDHMS );\n\nmy @datetime = AddDeltaDHMS( TodayandNow(), -1, 0, 0, 0 );\n\nprint \"@datetime\\n\";\n\nMost people try to use the time rather than the calendar to figure out\ndates, but that assumes that days are twenty-four hours each. For most\npeople, there are two days a year when they aren't: the switch to and\nfrom summer time throws this off. For example, the rest of the\nsuggestions will be wrong sometimes:\n\nStarting with Perl 5.10, Time::Piece and Time::Seconds are part of the\nstandard distribution, so you might think that you could do something\nlike this:\n\nuse Time::Piece;\nuse Time::Seconds;\n\nmy $yesterday = localtime() - ONEDAY; # WRONG\nprint \"Yesterday was $yesterday\\n\";\n\nThe Time::Piece module exports a new \"localtime\" that returns an object,\nand Time::Seconds exports the \"ONEDAY\" constant that is a set number of\nseconds. This means that it always gives the time 24 hours ago, which is\nnot always yesterday. This can cause problems around the end of daylight\nsaving time when there's one day that is 25 hours long.\n\nYou have the same problem with Time::Local, which will give the wrong\nanswer for those same special cases:\n\n# contributed by Gunnar Hjalmarsson\nuse Time::Local;\nmy $today = timelocal 0, 0, 12, ( localtime )[3..5];\nmy ($d, $m, $y) = ( localtime $today-86400 )[3..5]; # WRONG\nprintf \"Yesterday: %d-%02d-%02d\\n\", $y+1900, $m+1, $d;\n\nHow do I remove consecutive pairs of characters?\n(contributed by brian d foy)\n\nYou can use the substitution operator to find pairs of characters (or\nruns of characters) and replace them with a single instance. In this\nsubstitution, we find a character in \"(.)\". The memory parentheses store\nthe matched character in the back-reference \"\\g1\" and we use that to\nrequire that the same thing immediately follow it. We replace that part\nof the string with the character in $1.\n\ns/(.)\\g1/$1/g;\n\nWe can also use the transliteration operator, \"tr///\". In this example,\nthe search list side of our \"tr///\" contains nothing, but the \"c\" option\ncomplements that so it contains everything. The replacement list also\ncontains nothing, so the transliteration is almost a no-op since it\nwon't do any replacements (or more exactly, replace the character with\nitself). However, the \"s\" option squashes duplicated and consecutive\ncharacters in the string so a character does not show up next to itself\n\nmy $str = 'Haarlem';   # in the Netherlands\n$str =~ tr///cs;       # Now Harlem, like in New York\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 find matching/nesting anything?\nTo find something between two single characters, a pattern like\n\"/x([^x]*)x/\" will get the intervening bits in $1. For multiple ones,\nthen something more like \"/alpha(.*?)omega/\" would be needed. For nested\npatterns and/or balanced expressions, see the so-called (?PARNO)\nconstruct (available since perl 5.10). The CPAN module Regexp::Common\ncan help to build such regular expressions (see in particular\nRegexp::Common::balanced and Regexp::Common::delimited).\n\nMore complex cases will require to write a parser, probably using a\nparsing module from CPAN, like Regexp::Grammars, Parse::RecDescent,\nParse::Yapp, Text::Balanced, or Marpa::R2.\n\nHow do I reformat a paragraph?\nUse Text::Wrap (part of the standard Perl distribution):\n\nuse Text::Wrap;\nprint wrap(\"\\t\", '  ', @paragraphs);\n\nThe paragraphs you give to Text::Wrap should not contain embedded\nnewlines. Text::Wrap doesn't justify the lines (flush-right).\n\nOr use the CPAN module Text::Autoformat. Formatting files can be easily\ndone by making a shell alias, like so:\n\nalias fmt=\"perl -i -MText::Autoformat -n0777 \\\n-e 'print autoformat $, {all=>1}' $*\"\n\nSee the documentation for Text::Autoformat to appreciate its many\ncapabilities.\n\nHow can I access or change N characters of a string?\nYou can access the first characters of a string with substr(). To get\nthe first character, for example, start at position 0 and grab the\nstring of length 1.\n\nmy $string = \"Just another Perl Hacker\";\nmy $firstchar = substr( $string, 0, 1 );  #  'J'\n\nTo change part of a string, you can use the optional fourth argument\nwhich is the replacement string.\n\nsubstr( $string, 13, 4, \"Perl 5.8.0\" );\n\nYou can also use substr() as an lvalue.\n\nsubstr( $string, 13, 4 ) =  \"Perl 5.8.0\";\n\nHow do I change the Nth occurrence of something?\nYou have to keep track of N yourself. For example, let's say you want to\nchange the fifth occurrence of \"whoever\" or \"whomever\" into \"whosoever\"\nor \"whomsoever\", case insensitively. These all assume that $ contains\nthe string to be altered.\n\n$count = 0;\ns{((whom?)ever)}{\n++$count == 5       # is it the 5th?\n? \"${2}soever\"  # yes, swap\n: $1            # renege and leave it there\n}ige;\n\nIn the more general case, you can use the \"/g\" modifier in a \"while\"\nloop, keeping count of matches.\n\n$WANT = 3;\n$count = 0;\n$ = \"One fish two fish red fish blue fish\";\nwhile (/(\\w+)\\s+fish\\b/gi) {\nif (++$count == $WANT) {\nprint \"The third fish is a $1 one.\\n\";\n}\n}\n\nThat prints out: \"The third fish is a red one.\" You can also use a\nrepetition count and repeated pattern like this:\n\n/(?:\\w+\\s+fish\\s+){2}(\\w+)\\s+fish/i;\n\nHow can I count the number of occurrences of a substring within a string?\nThere are a number of ways, with varying efficiency. If you want a count\nof a certain single character (X) within a string, you can use the\n\"tr///\" function like so:\n\nmy $string = \"ThisXlineXhasXsomeXx'sXinXit\";\nmy $count = ($string =~ tr/X//);\nprint \"There are $count X characters in the string\";\n\nThis is fine if you are just looking for a single character. However, if\nyou are trying to count multiple character substrings within a larger\nstring, \"tr///\" won't work. What you can do is wrap a while() loop\naround a global pattern match. For example, let's count negative\nintegers:\n\nmy $string = \"-9 55 48 -2 23 -76 4 14 -44\";\nmy $count = 0;\nwhile ($string =~ /-\\d+/g) { $count++ }\nprint \"There are $count negative numbers in the string\";\n\nAnother version uses a global match in list context, then assigns the\nresult to a scalar, producing a count of the number of matches.\n\nmy $count = () = $string =~ /-\\d+/g;\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 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\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 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\nWhat is the difference between $array[1] and @array[1]?\n(contributed by brian d foy)\n\nThe difference is the sigil, that special character in front of the\narray name. The \"$\" sigil means \"exactly one item\", while the \"@\" sigil\nmeans \"zero or more items\". The \"$\" gets you a single scalar, while the\n\"@\" gets you a list.\n\nThe confusion arises because people incorrectly assume that the sigil\ndenotes the variable type.\n\nThe $array[1] is a single-element access to the array. It's going to\nreturn the item in index 1 (or undef if there is no item there). If you\nintend to get exactly one element from the array, this is the form you\nshould use.\n\nThe @array[1] is an array slice, although it has only one index. You can\npull out multiple elements simultaneously by specifying additional\nindices as a list, like @array[1,4,3,0].\n\nUsing a slice on the lefthand side of the assignment supplies list\ncontext to the righthand side. This can lead to unexpected results. For\ninstance, if you want to read a single line from a filehandle, assigning\nto a scalar value is fine:\n\n$array[1] = <STDIN>;\n\nHowever, in list context, the line input operator returns all of the\nlines as a list. The first line goes into @array[1] and the rest of the\nlines mysteriously disappear:\n\n@array[1] = <STDIN>;  # most likely not what you want\n\nEither the \"use warnings\" pragma or the -w flag will warn you when you\nuse an array slice with a single index.\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 do I compute the difference of two arrays? How do I compute the intersection of two arrays?\nUse a hash. Here's code to do both and more. It assumes that each\nelement is unique in a given array:\n\nmy (@union, @intersection, @difference);\nmy %count = ();\nforeach my $element (@array1, @array2) { $count{$element}++ }\nforeach my $element (keys %count) {\npush @union, $element;\npush @{ $count{$element} > 1 ? \\@intersection : \\@difference }, $element;\n}\n\nNote that this is the *symmetric difference*, that is, all elements in\neither A or in B but not in both. Think of it as an xor operation.\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 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\nWhy does defined() return true on empty arrays and hashes?\nThe short story is that you should probably only use defined on scalars\nor functions, not on aggregates (arrays and hashes). See \"defined\" in\nperlfunc in the 5.004 release or later of Perl for more detail.\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 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\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\nWhy don't my tied hashes make the defined/exists distinction?\nThis depends on the tied hash's implementation of EXISTS(). For example,\nthere isn't the concept of undef with hashes that are tied to DBM*\nfiles. It also means that exists() and defined() do the same thing with\na DBM* file, and what they end up doing is not what they do with\nordinary hashes.\n\nHow can I get the unique keys from two hashes?\nFirst you extract the keys from the hashes into lists, then solve the\n\"removing duplicates\" problem described above. For example:\n\nmy %seen = ();\nfor my $element (keys(%foo), keys(%bar)) {\n$seen{$element}++;\n}\nmy @uniq = keys %seen;\n\nOr more succinctly:\n\nmy @uniq = keys %{{%foo,%bar}};\n\nOr if you really want to save space:\n\nmy %seen = ();\nwhile (defined ($key = each %foo)) {\n$seen{$key}++;\n}\nwhile (defined ($key = each %bar)) {\n$seen{$key}++;\n}\nmy @uniq = keys %seen;\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\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 use a reference as a hash key?\n(contributed by brian d foy and Ben Morrow)\n\nHash keys are strings, so you can't really use a reference as the key.\nWhen you try to do that, perl turns the reference into its stringified\nform (for instance, HASH(0xDEADBEEF)). From there you can't get back the\nreference from the stringified form, at least without doing some extra\nwork on your own.\n\nRemember that the entry in the hash will still be there even if the\nreferenced variable goes out of scope, and that it is entirely possible\nfor Perl to subsequently allocate a different variable at the same\naddress. This will mean a new variable might accidentally be associated\nwith the value for an old.\n\nIf you have Perl 5.10 or later, and you just want to store a value\nagainst the reference for lookup later, you can use the core\nHash::Util::Fieldhash module. This will also handle renaming the keys if\nyou use multiple threads (which causes all variables to be reallocated\nat new addresses, changing their stringification), and\ngarbage-collecting the entries when the referenced variable goes out of\nscope.\n\nIf you actually need to be able to get a real reference back from each\nhash entry, you can use the Tie::RefHash module, which does the required\nwork for you.\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 can I prevent addition of unwanted keys into a hash?\nSince version 5.8.0, hashes can be *restricted* to a fixed number of\ngiven keys. Methods for creating and dealing with restricted hashes are\nexported by the Hash::Util module.\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 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 verify a credit card checksum?\nGet the Business::CreditCard module from CPAN.\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 set up a footer format to be used with write()?\nThere's no builtin way to do this, but perlform has a couple of\ntechniques to make it possible for the intrepid hacker.\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\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 can't I use \"C:\\temp\\foo\" in DOS paths? Why doesn't `C:\\temp\\foo.exe` work?\nWhoops! You just put a tab and a formfeed into that filename! Remember\nthat within double quoted strings (\"like\\this\"), the backslash is an\nescape character. The full list of these is in \"Quote and Quote-like\nOperators\" in perlop. Unsurprisingly, you don't have a file called\n\"c:(tab)emp(formfeed)oo\" or \"c:(tab)emp(formfeed)oo.exe\" on your legacy\nDOS filesystem.\n\nEither single-quote your strings, or (preferably) use forward slashes.\nSince all DOS and Windows versions since something like MS-DOS 2.0 or so\nhave treated \"/\" and \"\\\" the same in a path, you might as well use the\none that doesn't clash with Perl--or the POSIX shell, ANSI C and C++,\nawk, Tcl, Java, or Python, just to mention a few. POSIX paths are more\nportable, too.\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"
                    }
                ]
            },
            "Found in /usr/share/perl/5.38/pod/perlfaq6.pod": {
                "content": "How 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 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\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\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 don't word-boundary searches with \"\\b\" work for me?\n(contributed by brian d foy)\n\nEnsure that you know what \\b really does: it's the boundary between a\nword character, \\w, and something that isn't a word character. That\nthing that isn't a word character might be \\W, but it can also be the\nstart or end of the string.\n\nIt's not (not!) the boundary between whitespace and non-whitespace, and\nit's not the stuff between words we use to create sentences.\n\nIn regex speak, a word boundary (\\b) is a \"zero width assertion\",\nmeaning that it doesn't represent a character in the string, but a\ncondition at a certain position.\n\nFor the regular expression, /\\bPerl\\b/, there has to be a word boundary\nbefore the \"P\" and after the \"l\". As long as something other than a word\ncharacter precedes the \"P\" and succeeds the \"l\", the pattern will match.\nThese strings match /\\bPerl\\b/.\n\n\"Perl\"    # no word char before \"P\" or after \"l\"\n\"Perl \"   # same as previous (space is not a word char)\n\"'Perl'\"  # the \"'\" char is not a word char\n\"Perl's\"  # no word char before \"P\", non-word char after \"l\"\n\nThese strings do not match /\\bPerl\\b/.\n\n\"Perl\"   # \"\" is a word char!\n\"Perler\"  # no word char before \"P\", but one after \"l\"\n\nYou don't have to use \\b to match words though. You can look for\nnon-word characters surrounded by word characters. These strings match\nthe pattern /\\b'\\b/.\n\n\"don't\"   # the \"'\" char is surrounded by \"n\" and \"t\"\n\"qep'a'\"  # the \"'\" char is surrounded by \"p\" and \"a\"\n\nThese strings do not match /\\b'\\b/.\n\n\"foo'\"    # there is no word char after non-word \"'\"\n\nYou can also use the complement of \\b, \\B, to specify that there should\nnot be a word boundary.\n\nIn the pattern /\\Bam\\B/, there must be a word character before the \"a\"\nand after the \"m\". These patterns match /\\Bam\\B/:\n\n\"llama\"   # \"am\" surrounded by word chars\n\"Samuel\"  # same\n\nThese strings do not match /\\Bam\\B/\n\n\"Sam\"      # no word boundary before \"a\", but one after \"m\"\n\"I am Sam\" # \"am\" surrounded by non-word chars\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",
                "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\nWhy 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 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\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\nWhat's the difference between dynamic and lexical (static) scoping? Between local() and my()?",
                "subsections": [
                    {
                        "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": "What'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"
                    }
                ]
            },
            "Found in /usr/share/perl/5.38/pod/perlfaq8.pod": {
                "content": "How do I find out which operating system I'm running under?\nThe $^O variable ($OSNAME if you use \"English\") contains an indication\nof the name of the operating system (not its release number) that your\nperl binary was built for.\n\nHow do I do fancy stuff with the keyboard/screen/mouse?\nHow you access/control keyboards, screens, and pointing devices (\"mice\")\nis system-dependent. Try the following modules:\n\nKeyboard\nTerm::Cap               Standard perl distribution\nTerm::ReadKey           CPAN\nTerm::ReadLine::Gnu     CPAN\nTerm::ReadLine::Perl    CPAN\nTerm::Screen            CPAN\n\nScreen\nTerm::Cap               Standard perl distribution\nCurses                  CPAN\nTerm::ANSIColor         CPAN\n\nMouse\nTk                      CPAN\nWx                      CPAN\nGtk2                    CPAN\nQt4                     kdebindings4 package\n\nSome of these specific cases are shown as examples in other answers in\nthis section of the perlfaq.\n\nHow do I read just one key without waiting for a return key?\nControlling input buffering is a remarkably system-dependent matter. On\nmany systems, you can just use the stty command as shown in \"getc\" in\nperlfunc, but as you see, that's already getting you into portability\nsnags.\n\nopen(TTY, \"+</dev/tty\") or die \"no tty: $!\";\nsystem \"stty  cbreak </dev/tty >/dev/tty 2>&1\";\n$key = getc(TTY);        # perhaps this works\n# OR ELSE\nsysread(TTY, $key, 1);    # probably this does\nsystem \"stty -cbreak </dev/tty >/dev/tty 2>&1\";\n\nThe Term::ReadKey module from CPAN offers an easy-to-use interface that\nshould be more efficient than shelling out to stty for each key. It even\nincludes limited support for Windows.\n\nuse Term::ReadKey;\nReadMode('cbreak');\n$key = ReadKey(0);\nReadMode('normal');\n\nHowever, using the code requires that you have a working C compiler and\ncan use it to build and install a CPAN module. Here's a solution using\nthe standard POSIX module, which is already on your system (assuming\nyour system supports POSIX).\n\nuse HotKey;\n$key = readkey();\n\nAnd here's the \"HotKey\" module, which hides the somewhat mystifying\ncalls to manipulate the POSIX termios structures.\n\n# HotKey.pm\npackage HotKey;\n\nuse strict;\nuse warnings;\n\nuse parent 'Exporter';\nour @EXPORT = qw(cbreak cooked readkey);\n\nuse POSIX qw(:termiosh);\nmy ($term, $oterm, $echo, $noecho, $fdstdin);\n\n$fdstdin = fileno(STDIN);\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);  # ok, so i don't want echo either\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 readkey {\nmy $key = '';\ncbreak();\nsysread(STDIN, $key, 1);\ncooked();\nreturn $key;\n}\n\nEND { cooked() }\n\n1;\n\nHow do I ask the user for a password?\n(This question has nothing to do with the web. See a different FAQ for\nthat.)\n\nThere's an example of this in \"crypt\" in perlfunc. First, you put the\nterminal into \"no echo\" mode, then just read the password normally. You\nmay do this with an old-style ioctl() function, POSIX terminal control\n(see POSIX or its documentation the Camel Book), or a call to the stty\nprogram, with varying degrees of portability.\n\nYou can also do this for most systems using the Term::ReadKey module\nfrom CPAN, which is easier to use and in theory more portable.\n\nuse Term::ReadKey;\n\nReadMode('noecho');\nmy $password = ReadLine(0);\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 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 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\nHow can I open a pipe both to and from a command?\nThe IPC::Open2 module (part of the standard perl distribution) is an\neasy-to-use approach that internally uses pipe(), fork(), and exec() to\ndo the job. Make sure you read the deadlock warnings in its\ndocumentation, though (see IPC::Open2). See \"Bidirectional Communication\nwith Another Process\" in perlipc and \"Bidirectional Communication with\nYourself\" in perlipc\n\nYou may also use the IPC::Open3 module (part of the standard perl\ndistribution), but be warned that it has a different order of arguments\nfrom IPC::Open2 (see IPC::Open3).\n\nWhy can't I get the output of a command with system()?\nYou're confusing the purpose of system() and backticks (``). system()\nruns a command and returns exit status information (as a 16 bit value:\nthe low 7 bits are the signal the process died from, if any, and the\nhigh 8 bits are the actual exit value). Backticks (``) run a command and\nreturn what it sent to STDOUT.\n\nmy $exitstatus   = system(\"mail-users\");\nmy $outputstring = `ls`;\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\nWhy can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?\nThis happens only if your perl is compiled to use stdio instead of\nperlio, which is the default. Some (maybe all?) stdios set error and eof\nflags that you may need to clear. The POSIX module defines clearerr()\nthat you can use. That is the technically correct way to do it. Here are\nsome less reliable workarounds:\n\n1   Try keeping around the seekpointer and go there, like this:\n\nmy $where = tell($logfh);\nseek($logfh, $where, 0);\n\n2   If that doesn't work, try seeking to a different part of the file\nand then back.\n\n3   If that doesn't work, try seeking to a different part of the file,\nreading something, and then seeking back.\n\n4   If that doesn't work, give up on your stdio package and use sysread.\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\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 fork a daemon process?\nIf by daemon process you mean one that's detached (disassociated from\nits tty), then the following process is reported to work on most Unixish\nsystems. Non-Unix users should check their YourOS::Process module for\nother solutions.\n\n*   Open /dev/tty and use the TIOCNOTTY ioctl on it. See tty(1) for\ndetails. Or better yet, you can just use the POSIX::setsid()\nfunction, so you don't have to worry about process groups.\n\n*   Change directory to /\n\n*   Reopen STDIN, STDOUT, and STDERR so they're not connected to the old\ntty.\n\n*   Background yourself like this:\n\nfork && exit;\n\nThe Proc::Daemon module, available from CPAN, provides a function to\nperform these actions for you.\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 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\nWhat's the difference between require and use?\n(contributed by brian d foy)\n\nPerl runs \"require\" statement at run-time. Once Perl loads, compiles,\nand runs the file, it doesn't do anything else. The \"use\" statement is\nthe same as a \"require\" run at compile-time, but Perl also calls the\n\"import\" method for the loaded package. These two are the same:\n\nuse MODULE qw(import list);\n\nBEGIN {\nrequire MODULE;\nMODULE->import(import list);\n}\n\nHowever, you can suppress the \"import\" by using an explicit, empty\nimport list. Both of these still happen at compile-time:\n\nuse MODULE ();\n\nBEGIN {\nrequire MODULE;\n}\n\nSince \"use\" will also call the \"import\" method, the actual value for\n\"MODULE\" must be a bareword. That is, \"use\" cannot load files by name,\nalthough \"require\" can:\n\nrequire \"$ENV{HOME}/lib/Foo.pm\"; # no @INC searching!\n\nSee the entry for \"use\" in perlfunc for more details.\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\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 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 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 find out my hostname, domainname, or IP address?\n(contributed by brian d foy)\n\nThe Net::Domain module, which is part of the Standard Library starting\nin Perl 5.7.3, can get you the fully qualified domain name (FQDN), the\nhost name, or the domain name.\n\nuse Net::Domain qw(hostname hostfqdn hostdomain);\n\nmy $host = hostfqdn();\n\nThe Sys::Hostname module, part of the Standard Library, can also get the\nhostname:\n\nuse Sys::Hostname;\n\n$host = hostname();\n\nThe Sys::Hostname::Long module takes a different approach and tries\nharder to return the fully qualified hostname:\n\nuse Sys::Hostname::Long 'hostnamelong';\n\nmy $hostname = hostnamelong();\n\nTo get the IP address, you can use the \"gethostbyname\" built-in function\nto turn the name into a number. To turn that number into the dotted\noctet form (a.b.c.d) that most people expect, use the \"inetntoa\"\nfunction from the Socket module, which also comes with perl.\n\nuse Socket;\n\nmy $address = inetntoa(\nscalar gethostbyname( $host || 'localhost' )\n);\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",
                "subsections": []
            }
        }
    }
}