{
    "content": [
        {
            "type": "text",
            "text": "# D (perldoc)\n\n## Sections\n\n- **Found in /usr/share/perl/5.34/pod/perlfaq1.pod**\n- **Found in /usr/share/perl/5.34/pod/perlfaq2.pod**\n- **Found in /usr/share/perl/5.34/pod/perlfaq3.pod**\n- **Found in /usr/share/perl/5.34/pod/perlfaq4.pod**\n- **Found in /usr/share/perl/5.34/pod/perlfaq5.pod** (2 subsections)\n- **Found in /usr/share/perl/5.34/pod/perlfaq6.pod**\n- **Found in /usr/share/perl/5.34/pod/perlfaq7.pod** (2 subsections)\n- **Found in /usr/share/perl/5.34/pod/perlfaq8.pod** (2 subsections)\n- **Found in /usr/share/perl/5.34/pod/perlfaq9.pod**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "D",
        "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.34/pod/perlfaq1.pod",
                "lines": 172,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq2.pod",
                "lines": 108,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq3.pod",
                "lines": 601,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq4.pod",
                "lines": 2256,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq5.pod",
                "lines": 841,
                "subsections": [
                    {
                        "name": "touch",
                        "lines": 4
                    },
                    {
                        "name": "utime",
                        "lines": 448
                    }
                ]
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq6.pod",
                "lines": 788,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq7.pod",
                "lines": 93,
                "subsections": [
                    {
                        "name": "my",
                        "lines": 311
                    },
                    {
                        "name": "local",
                        "lines": 402
                    }
                ]
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq8.pod",
                "lines": 334,
                "subsections": [
                    {
                        "name": "passwd",
                        "lines": 97
                    },
                    {
                        "name": "pwd_mkdb",
                        "lines": 765
                    }
                ]
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq9.pod",
                "lines": 359,
                "subsections": []
            }
        ],
        "sections": {
            "Found in /usr/share/perl/5.34/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\nHow does Perl compare with other languages like Java, Python, REXX, Scheme, or Tcl?\nPerl can be used for almost any coding problem, even ones which require\nintegrating specialist C code for extra speed. As with any tool it can\nbe used well or badly. Perl has many strengths, and a few weaknesses,\nprecisely which areas are good and bad is often a personal choice.\n\nWhen choosing a language you should also be influenced by the resources\n<http://www.cpan.org/>, testing culture <http://www.cpantesters.org/>\nand community <http://www.perl.org/community.html> which surrounds it.\n\nFor comparisons to a specific language it is often best to create a\nsmall project in both languages and compare the results, make sure to\nuse all the resources <http://www.cpan.org/> of each language, as a\nlanguage is far more than just it's syntax.\n\nCan I do [task] in Perl?\nPerl is flexible and extensible enough for you to use on virtually any\ntask, from one-line file-processing tasks to large, elaborate systems.\n\nFor many people, Perl serves as a great replacement for shell scripting.\nFor others, it serves as a convenient, high-level replacement for most\nof what they'd program in low-level languages like C or C++. It's\nultimately up to you (and possibly your management) which tasks you'll\nuse Perl for and which you won't.\n\nIf you have a library that provides an API, you can make any component\nof it available as just another Perl function or variable using a Perl\nextension written in C or C++ and dynamically linked into your main perl\ninterpreter. You can also go the other direction, and write your main\nprogram in C or C++, and then link in some Perl code on the fly, to\ncreate a powerful application. See perlembed.\n\nThat said, there will always be small, focused, special-purpose\nlanguages dedicated to a specific problem domain that are simply more\nconvenient for certain kinds of problems. Perl tries to be all things to\nall people, but nothing special to anyone. Examples of specialized\nlanguages that come to mind include prolog and matlab.\n\nWhen shouldn't I program in Perl?\nOne good reason is when you already have an existing application written\nin another language that's all done (and done well), or you have an\napplication language specifically designed for a certain task (e.g.\nprolog, make).\n\nIf you find that you need to speed up a specific part of a Perl\napplication (not something you often need) you may want to use C, but\nyou can access this from your Perl code with perlxs.\n\nWhat's the difference between \"perl\" and \"Perl\"?\n\"Perl\" is the name of the language. Only the \"P\" is capitalized. The\nname of the interpreter (the program which runs the Perl script) is\n\"perl\" with a lowercase \"p\".\n\nYou may or may not choose to follow this usage. But never write \"PERL\",\nbecause perl is not an acronym.\n",
                "subsections": []
            },
            "Found in /usr/share/perl/5.34/pod/perlfaq2.pod": {
                "content": "What machines support Perl? Where do I get it?\nThe standard release of Perl (the one maintained by the Perl development\nteam) is distributed only in source code form. You can find the latest\nreleases at <http://www.cpan.org/src/>.\n\nPerl builds and runs on a bewildering number of platforms. Virtually all\nknown and current Unix derivatives are supported (perl's native\nplatform), as are other systems like VMS, DOS, OS/2, Windows, QNX, BeOS,\nOS X, MPE/iX and the Amiga.\n\nBinary distributions for some proprietary platforms can be found\n<http://www.cpan.org/ports/> directory. Because these are not part of\nthe standard distribution, they may and in fact do differ from the base\nperl port in a variety of ways. You'll have to check their respective\nrelease notes to see just what the differences are. These differences\ncan be either positive (e.g. extensions for the features of the\nparticular platform that are not supported in the source release of\nperl) or negative (e.g. might be based upon a less current source\nrelease of perl).\n\nI don't have a C compiler. How can I build my own Perl interpreter?\nFor Windows, use a binary version of Perl, Strawberry Perl\n<http://strawberryperl.com/> and ActivePerl\n<http://www.activestate.com/activeperl> come with a bundled C compiler.\n\nOtherwise if you really do want to build Perl, you need to get a binary\nversion of \"gcc\" for your system first. Use a search engine to find out\nhow to do this for your operating system.\n\nI copied the Perl binary from one machine to another, but scripts don't work.\nThat's probably because you forgot libraries, or library paths differ.\nYou really should build the whole distribution on the machine it will\neventually live on, and then type \"make install\". Most other approaches\nare doomed to failure.\n\nOne simple way to check that things are in the right place is to print\nout the hard-coded @INC that perl looks through for libraries:\n\n% perl -le 'print for @INC'\n\nIf this command lists any paths that don't exist on your system, then\nyou may need to move the appropriate libraries to these locations, or\ncreate symbolic links, aliases, or shortcuts appropriately. @INC is also\nprinted as part of the output of\n\n% perl -V\n\nYou might also want to check out \"How do I keep my own module/library\ndirectory?\" in perlfaq8.\n\nI grabbed the sources and tried to compile but gdbm/dynamic loading/malloc/linking/... failed. How do I make it work?\nRead the INSTALL file, which is part of the source distribution. It\ndescribes in detail how to cope with most idiosyncrasies that the\n\"Configure\" script can't work around for any given system or\narchitecture.\n\nWhat modules and extensions are available for Perl? What is CPAN?\nCPAN stands for Comprehensive Perl Archive Network, a multi-gigabyte\narchive replicated on hundreds of machines all over the world. CPAN\ncontains tens of thousands of modules and extensions, source code and\ndocumentation, designed for *everything* from commercial database\ninterfaces to keyboard/screen control and running large web sites.\n\nYou can search CPAN on <http://metacpan.org>.\n\nThe master web site for CPAN is <http://www.cpan.org/>,\n<http://www.cpan.org/SITES.html> lists all mirrors.\n\nSee the CPAN FAQ at <http://www.cpan.org/misc/cpan-faq.html> for answers\nto the most frequently asked questions about CPAN.\n\nThe Task::Kensho module has a list of recommended modules which you\nshould review as a good starting point.\n\nWhich Perl blogs should I read?\nPerl News <http://perlnews.org/> covers some of the major events in the\nPerl world, Perl Weekly <http://perlweekly.com/> is a weekly e-mail (and\nRSS feed) of hand-picked Perl articles.\n\n<http://blogs.perl.org/> hosts many Perl blogs, there are also several\nblog aggregators: Perlsphere <http://perlsphere.net/> and IronMan\n<http://ironman.enlightenedperl.org/> are two of them.\n\nWhere do I send bug reports?\n(contributed by brian d foy)\n\nFirst, ensure that you've found an actual bug. Second, ensure you've\nfound an actual bug.\n\nIf you've found a bug with the perl interpreter or one of the modules in\nthe standard library (those that come with Perl), you can submit a bug\nreport to the GitHub issue tracker at\n<https://github.com/Perl/perl5/issues>.\n\nTo determine if a module came with your version of Perl, you can install\nand use the Module::CoreList module. It has the information about the\nmodules (with their versions) included with each release of Perl.\n\nEvery CPAN module has a bug tracker set up in RT, <http://rt.cpan.org>.\nYou can submit bugs to RT either through its web interface or by email.\nTo email a bug report, send it to bug-<distribution-name>@rt.cpan.org .\nFor example, if you wanted to report a bug in Business::ISBN, you could\nsend a message to bug-Business-ISBN@rt.cpan.org .\n\nSome modules might have special reporting requirements, such as a GitHub\nor Google Code tracking system, so you should check the module\ndocumentation too.\n",
                "subsections": []
            },
            "Found in /usr/share/perl/5.34/pod/perlfaq3.pod": {
                "content": "How do I do (anything)?\nHave you looked at CPAN (see perlfaq2)? The chances are that someone has\nalready written a module that can solve your problem. Have you read the\nappropriate manpages? Here's a brief index:\n\nBasics\n\nperldata - Perl data types\nperlvar - Perl pre-defined variables\nperlsyn - Perl syntax\nperlop - Perl operators and precedence\nperlsub - Perl subroutines\n\nExecution\n\nperlrun - how to execute the Perl interpreter\nperldebug - Perl debugging\n\nFunctions\n\nperlfunc - Perl builtin functions\n\nObjects\n\nperlref - Perl references and nested data structures\nperlmod - Perl modules (packages and symbol tables)\nperlobj - Perl objects\nperltie - how to hide an object class in a simple variable\n\nData Structures\n\nperlref - Perl references and nested data structures\nperllol - Manipulating arrays of arrays in Perl\nperldsc - Perl Data Structures Cookbook\n\nModules\n\nperlmod - Perl modules (packages and symbol tables)\nperlmodlib - constructing new Perl modules and finding existing ones\n\nRegexes\n\nperlre - Perl regular expressions\nperlfunc - Perl builtin functions>\nperlop - Perl operators and precedence\nperllocale - Perl locale handling (internationalization and\nlocalization)\n\nMoving to perl5\n\nperltrap - Perl traps for the unwary\nperl\n\nLinking with C\n\nperlxstut - Tutorial for writing XSUBs\nperlxs - XS language reference manual\nperlcall - Perl calling conventions from C\nperlguts - Introduction to the Perl API\nperlembed - how to embed perl in your C program\n\nVarious\n<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> (not a man-page but\nstill useful, a collection of various essays on Perl techniques)\n\nA crude table of contents for the Perl manpage set is found in perltoc.\n\nHow do I find which modules are installed on my system?\nFrom the command line, you can use the \"cpan\" command's \"-l\" switch:\n\n$ cpan -l\n\nYou can also use \"cpan\"'s \"-a\" switch to create an autobundle file that\n\"CPAN.pm\" understands and can use to re-install every module:\n\n$ cpan -a\n\nInside a Perl program, you can use the ExtUtils::Installed module to\nshow all installed distributions, although it can take awhile to do its\nmagic. The standard library which comes with Perl just shows up as\n\"Perl\" (although you can get those with Module::CoreList).\n\nuse ExtUtils::Installed;\n\nmy $inst    = ExtUtils::Installed->new();\nmy @modules = $inst->modules();\n\nIf you want a list of all of the Perl module filenames, you can use\nFile::Find::Rule:\n\nuse File::Find::Rule;\n\nmy @files = File::Find::Rule->\nextras({follow => 1})->\nfile()->\nname( '*.pm' )->\nin( @INC )\n;\n\nIf you do not have that module, you can do the same thing with\nFile::Find which is part of the standard library:\n\nuse File::Find;\nmy @files;\n\nfind(\n{\nwanted => sub {\npush @files, $File::Find::fullname\nif -f $File::Find::fullname && /\\.pm$/\n},\nfollow => 1,\nfollowskip => 2,\n},\n@INC\n);\n\nprint join \"\\n\", @files;\n\nIf you simply need to check quickly to see if a module is available, you\ncan check for its documentation. If you can read the documentation the\nmodule is most likely installed. If you cannot read the documentation,\nthe module might not have any (in rare cases):\n\n$ perldoc Module::Name\n\nYou can also try to include the module in a one-liner to see if perl\nfinds it:\n\n$ perl -MModule::Name -e1\n\n(If you don't receive a \"Can't locate ... in @INC\" error message, then\nPerl found the module name you asked for.)\n\nHow do I debug my Perl programs?\n(contributed by brian d foy)\n\nBefore you do anything else, you can help yourself by ensuring that you\nlet Perl tell you about problem areas in your code. By turning on\nwarnings and strictures, you can head off many problems before they get\ntoo big. You can find out more about these in strict and warnings.\n\n#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nBeyond that, the simplest debugger is the \"print\" function. Use it to\nlook at values as you run your program:\n\nprint STDERR \"The value is [$value]\\n\";\n\nThe Data::Dumper module can pretty-print Perl data structures:\n\nuse Data::Dumper qw( Dumper );\nprint STDERR \"The hash is \" . Dumper( \\%hash ) . \"\\n\";\n\nPerl comes with an interactive debugger, which you can start with the\n\"-d\" switch. It's fully explained in perldebug.\n\nIf you'd like a graphical user interface and you have Tk, you can use\n\"ptkdb\". It's on CPAN and available for free.\n\nIf you need something much more sophisticated and controllable, Leon\nBrocard's Devel::ebug (which you can call with the \"-D\" switch as\n\"-Debug\") gives you the programmatic hooks into everything you need to\nwrite your own (without too much pain and suffering).\n\nYou can also use a commercial debugger such as Affrus (Mac OS X), Komodo\nfrom Activestate (Windows and Mac OS X), or EPIC (most platforms).\n\nHow do I profile my Perl programs?\n(contributed by brian d foy, updated Fri Jul 25 12:22:26 PDT 2008)\n\nThe \"Devel\" namespace has several modules which you can use to profile\nyour Perl programs.\n\nThe Devel::NYTProf (New York Times Profiler) does both statement and\nsubroutine profiling. It's available from CPAN and you also invoke it\nwith the \"-d\" switch:\n\nperl -d:NYTProf someperl.pl\n\nIt creates a database of the profile information that you can turn into\nreports. The \"nytprofhtml\" command turns the data into an HTML report\nsimilar to the Devel::Cover report:\n\nnytprofhtml\n\nYou might also be interested in using the Benchmark to measure and\ncompare code snippets.\n\nYou can read more about profiling in *Programming Perl*, chapter 20, or\n*Mastering Perl*, chapter 5.\n\nperldebguts documents creating a custom debugger if you need to create a\nspecial sort of profiler. brian d foy describes the process in *The Perl\nJournal*, \"Creating a Perl Debugger\", <http://www.ddj.com/184404522> ,\nand \"Profiling in Perl\" <http://www.ddj.com/184404580> .\n\nPerl.com has two interesting articles on profiling: \"Profiling Perl\", by\nSimon Cozens, <https://www.perl.com/pub/2004/06/25/profiling.html/> and\n\"Debugging and Profiling modperl Applications\", by Frank Wiles,\n<http://www.perl.com/pub/a/2006/02/09/debugmodperl.html> .\n\nRandal L. Schwartz writes about profiling in \"Speeding up Your Perl\nPrograms\" for *Unix Review*,\n<http://www.stonehenge.com/merlyn/UnixReview/col49.html> , and\n\"Profiling in Template Toolkit via Overriding\" for *Linux Magazine*,\n<http://www.stonehenge.com/merlyn/LinuxMag/col75.html> .\n\nHow do I cross-reference my Perl programs?\nThe B::Xref module can be used to generate cross-reference reports for\nPerl programs.\n\nperl -MO=Xref[,OPTIONS] scriptname.plx\n\nIs there an IDE or Windows Perl Editor?\nPerl programs are just plain text, so any editor will do.\n\nIf you're on Unix, you already have an IDE--Unix itself. The Unix\nphilosophy is the philosophy of several small tools that each do one\nthing and do it well. It's like a carpenter's toolbox.\n\nIf you want an IDE, check the following (in alphabetical order, not\norder of preference):\n\nEclipse\n<http://e-p-i-c.sf.net/>\n\nThe Eclipse Perl Integration Project integrates Perl\nediting/debugging with Eclipse.\n\nEnginsite\n<http://www.enginsite.com/>\n\nPerl Editor by EngInSite is a complete integrated development\nenvironment (IDE) for creating, testing, and debugging Perl scripts;\nthe tool runs on Windows 9x/NT/2000/XP or later.\n\nIntelliJ IDEA\n<https://plugins.jetbrains.com/plugin/7796>\n\nCamelcade plugin provides Perl5 support in IntelliJ IDEA and other\nJetBrains IDEs.\n\nKephra\n<http://kephra.sf.net>\n\nGUI editor written in Perl using wxWidgets and Scintilla with lots\nof smaller features. Aims for a UI based on Perl principles like\nTIMTOWTDI and \"easy things should be easy, hard things should be\npossible\".\n\nKomodo\n<http://www.ActiveState.com/Products/Komodo/>\n\nActiveState's cross-platform (as of October 2004, that's Windows,\nLinux, and Solaris), multi-language IDE has Perl support, including\na regular expression debugger and remote debugging.\n\nNotepad++\n<http://notepad-plus.sourceforge.net/>\n\nOpen Perl IDE\n<http://open-perl-ide.sourceforge.net/>\n\nOpen Perl IDE is an integrated development environment for writing\nand debugging Perl scripts with ActiveState's ActivePerl\ndistribution under Windows 95/98/NT/2000.\n\nOptiPerl\n<http://www.optiperl.com/>\n\nOptiPerl is a Windows IDE with simulated CGI environment, including\ndebugger and syntax-highlighting editor.\n\nPadre\n<http://padre.perlide.org/>\n\nPadre is cross-platform IDE for Perl written in Perl using wxWidgets\nto provide a native look and feel. It's open source under the\nArtistic License. It is one of the newer Perl IDEs.\n\nPerlBuilder\n<http://www.solutionsoft.com/perl.htm>\n\nPerlBuilder is an integrated development environment for Windows\nthat supports Perl development.\n\nvisiPerl+\n<http://helpconsulting.net/visiperl/index.html>\n\nFrom Help Consulting, for Windows.\n\nVisual Perl\n<http://www.activestate.com/Products/VisualPerl/>\n\nVisual Perl is a Visual Studio.NET plug-in from ActiveState.\n\nZeus\n<http://www.zeusedit.com/lookmain.html>\n\nZeus for Windows is another Win32 multi-language editor/IDE that\ncomes with support for Perl.\n\nFor editors: if you're on Unix you probably have vi or a vi clone\nalready, and possibly an emacs too, so you may not need to download\nanything. In any emacs the cperl-mode (M-x cperl-mode) gives you perhaps\nthe best available Perl editing mode in any editor.\n\nIf you are using Windows, you can use any editor that lets you work with\nplain text, such as NotePad or WordPad. Word processors, such as\nMicrosoft Word or WordPerfect, typically do not work since they insert\nall sorts of behind-the-scenes information, although some allow you to\nsave files as \"Text Only\". You can also download text editors designed\nspecifically for programming, such as Textpad (\n<http://www.textpad.com/> ) and UltraEdit ( <http://www.ultraedit.com/>\n), among others.\n\nIf you are using MacOS, the same concerns apply. MacPerl (for Classic\nenvironments) comes with a simple editor. Popular external editors are\nBBEdit ( <http://www.barebones.com/products/bbedit/> ) or Alpha (\n<http://www.his.com/~jguyer/Alpha/Alpha8.html> ). MacOS X users can use\nUnix editors as well.\n\nGNU Emacs\n<http://www.gnu.org/software/emacs/windows/ntemacs.html>\n\nMicroEMACS\n<http://www.microemacs.de/>\n\nXEmacs\n<http://www.xemacs.org/Download/index.html>\n\nJed <http://space.mit.edu/~davis/jed/>\n\nor a vi clone such as\n\nVim <http://www.vim.org/>\n\nVile\n<http://invisible-island.net/vile/vile.html>\n\nThe following are Win32 multilanguage editor/IDEs that support Perl:\n\nMultiEdit\n<http://www.MultiEdit.com/>\n\nSlickEdit\n<http://www.slickedit.com/>\n\nConTEXT\n<http://www.contexteditor.org/>\n\nThere is also a toyedit Text widget based editor written in Perl that is\ndistributed with the Tk module on CPAN. The ptkdb (\n<http://ptkdb.sourceforge.net/> ) is a Perl/Tk-based debugger that acts\nas a development environment of sorts. Perl Composer (\n<http://perlcomposer.sourceforge.net/> ) is an IDE for Perl/Tk GUI\ncreation.\n\nIn addition to an editor/IDE you might be interested in a more powerful\nshell environment for Win32. Your options include\n\nbash\nfrom the Cygwin package ( <http://cygwin.com/> )\n\nzsh <http://www.zsh.org/>\n\nCygwin is covered by the GNU General Public License (but that shouldn't\nmatter for Perl use). Cygwin contains (in addition to the shell) a\ncomprehensive set of standard Unix toolkit utilities.\n\nBBEdit and TextWrangler\nare text editors for OS X that have a Perl sensitivity mode (\n<http://www.barebones.com/> ).\n\nWhere can I get perl-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\nIs it safe to return a reference to local or lexical data?\nYes. Perl's garbage collection system takes care of this so everything\nworks out right.\n\nsub makeone {\nmy @a = ( 1 .. 10 );\nreturn \\@a;\n}\n\nfor ( 1 .. 10 ) {\npush @many, makeone();\n}\n\nprint $many[4][5], \"\\n\";\n\nprint \"@many\\n\";\n\nHow can I hide the source for my Perl program?\nDelete it. :-) Seriously, there are a number of (mostly unsatisfactory)\nsolutions with varying levels of \"security\".\n\nFirst of all, however, you *can't* take away read permission, because\nthe source code has to be readable in order to be compiled and\ninterpreted. (That doesn't mean that a CGI script's source is readable\nby people on the web, though--only by people with access to the\nfilesystem.) So you have to leave the permissions at the socially\nfriendly 0755 level.\n\nSome people regard this as a security problem. If your program does\ninsecure things and relies on people not knowing how to exploit those\ninsecurities, it is not secure. It is often possible for someone to\ndetermine the insecure things and exploit them without viewing the\nsource. Security through obscurity, the name for hiding your bugs\ninstead of fixing them, is little security indeed.\n\nYou can try using encryption via source filters (Starting from Perl 5.8\nthe Filter::Simple and Filter::Util::Call modules are included in the\nstandard distribution), but any decent programmer will be able to\ndecrypt it. You can try using the byte code compiler and interpreter\ndescribed later in perlfaq3, but the curious might still be able to\nde-compile it. You can try using the native-code compiler described\nlater, but crackers might be able to disassemble it. These pose varying\ndegrees of difficulty to people wanting to get at your code, but none\ncan definitively conceal it (true of every language, not just Perl).\n\nIt is very easy to recover the source of Perl programs. You simply feed\nthe program to the perl interpreter and use the modules in the B::\nhierarchy. The B::Deparse module should be able to defeat most attempts\nto hide source. Again, this is not unique to Perl.\n\nIf you're concerned about people profiting from your code, then the\nbottom line is that nothing but a restrictive license will give you\nlegal security. License your software and pepper it with threatening\nstatements like \"This is unpublished proprietary software of XYZ Corp.\nYour access to it does not give you permission to use it blah blah\nblah.\" We are not lawyers, of course, so you should see a lawyer if you\nwant to be sure your license's wording will stand up in court.\n\nHow can I compile my Perl program into byte code or C?\n(contributed by brian d foy)\n\nIn general, you can't do this. There are some things that may work for\nyour situation though. People usually ask this question because they\nwant to distribute their works without giving away the source code, and\nmost solutions trade disk space for convenience. You probably won't see\nmuch of a speed increase either, since most solutions simply bundle a\nPerl interpreter in the final product (but see \"How can I make my Perl\nprogram run faster?\").\n\nThe Perl Archive Toolkit is Perl's analog to Java's JAR. It's freely\navailable and on CPAN ( <https://metacpan.org/pod/PAR> ).\n\nThere are also some commercial products that may work for you, although\nyou have to buy a license for them.\n\nThe Perl Dev Kit ( <http://www.activestate.com/Products/PerlDevKit/> )\nfrom ActiveState can \"Turn your Perl programs into ready-to-run\nexecutables for HP-UX, Linux, Solaris and Windows.\"\n\nPerl2Exe ( <http://www.indigostar.com/perl2exe.htm> ) is a command line\nprogram for converting perl scripts to executable files. It targets both\nWindows and Unix platforms.\n\nHow can I get \"#!perl\" to work on [MS-DOS,NT,...]?\nFor OS/2 just use\n\nextproc perl -S -yourswitches\n\nas the first line in \"*.cmd\" file (\"-S\" due to a bug in cmd.exe's\n\"extproc\" handling). For DOS one should first invent a corresponding\nbatch file and codify it in \"ALTERNATESHEBANG\" (see the dosish.h file\nin the source distribution for more information).\n\nThe Win95/NT installation, when using the ActiveState port of Perl, will\nmodify the Registry to associate the \".pl\" extension with the perl\ninterpreter. If you install another port, perhaps even building your own\nWin95/NT Perl from the standard sources by using a Windows port of gcc\n(e.g., with cygwin or mingw32), then you'll have to modify the Registry\nyourself. In addition to associating \".pl\" with the interpreter, NT\npeople can use: \"SET PATHEXT=%PATHEXT%;.PL\" to let them run the program\n\"install-linux.pl\" merely by typing \"install-linux\".\n\nUnder \"Classic\" MacOS, a perl program will have the appropriate Creator\nand Type, so that double-clicking them will invoke the MacPerl\napplication. Under Mac OS X, clickable apps can be made from any \"#!\"\nscript using Wil Sanchez' DropScript utility:\n<http://www.wsanchez.net/software/> .\n\n*IMPORTANT!*: Whatever you do, PLEASE don't get frustrated, and just\nthrow the perl interpreter into your cgi-bin directory, in order to get\nyour programs working for a web server. This is an EXTREMELY big\nsecurity risk. Take the time to figure out how to do it correctly.\n\nCan I write useful Perl programs on the command line?\nYes. Read perlrun for more information. Some examples follow. (These\nassume standard Unix shell quoting rules.)\n\n# sum first and last fields\nperl -lane 'print $F[0] + $F[-1]' *\n\n# identify text files\nperl -le 'for(@ARGV) {print if -f && -T }' *\n\n# remove (most) comments from C program\nperl -0777 -pe 's{/\\*.*?\\*/}{}gs' foo.c\n\n# make file a month younger than today, defeating reaper daemons\nperl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *\n\n# find first unused uid\nperl -le '$i++ while getpwuid($i); print $i'\n\n# display reasonable manpath\necho $PATH | perl -nl -072 -e '\ns![^/+]*$!man!&&-d&&!$s{$}++&&push@m,$;END{print\"@m\"}'\n\nOK, the last one was actually an Obfuscated Perl Contest entry. :-)\n\nWhy don't Perl one-liners work on my DOS/Mac/VMS system?\nThe problem is usually that the command interpreters on those systems\nhave rather different ideas about quoting than the Unix shells under\nwhich the one-liners were created. On some systems, you may have to\nchange single-quotes to double ones, which you must *NOT* do on Unix or\nPlan9 systems. You might also have to change a single % to a %%.\n\nFor example:\n\n# Unix (including Mac OS X)\nperl -e 'print \"Hello world\\n\"'\n\n# DOS, etc.\nperl -e \"print \\\"Hello world\\n\\\"\"\n\n# Mac Classic\nprint \"Hello world\\n\"\n(then Run \"Myscript\" or Shift-Command-R)\n\n# MPW\nperl -e 'print \"Hello world\\n\"'\n\n# VMS\nperl -e \"print \"\"Hello world\\n\"\"\"\n\nThe problem is that none of these examples are reliable: they depend on\nthe command interpreter. Under Unix, the first two often work. Under\nDOS, it's entirely possible that neither works. If 4DOS was the command\nshell, you'd probably have better luck like this:\n\nperl -e \"print <Ctrl-x>\"Hello world\\n<Ctrl-x>\"\"\n\nUnder the Mac, it depends which environment you are using. The MacPerl\nshell, or MPW, is much like Unix shells in its support for several\nquoting variants, except that it makes free use of the Mac's non-ASCII\ncharacters as control characters.\n\nUsing qq(), q(), and qx(), instead of \"double quotes\", 'single quotes',\nand `backticks`, may make one-liners easier to write.\n\nThere is no general solution to all of this. It is a mess.\n\n[Some of this answer was contributed by Kenneth Albanowski.]\n\nWhere can I learn about object-oriented Perl programming?\nA good place to start is perlootut, and you can use perlobj for\nreference.\n\nA good book on OO on Perl is the \"Object-Oriented Perl\" by Damian Conway\nfrom Manning Publications, or \"Intermediate Perl\" by Randal Schwartz,\nbrian d foy, and Tom Phoenix from O'Reilly Media.\n\nI've read perlembed, perlguts, etc., but I can't embed perl in my C program; what am I doing wrong?\nDownload the ExtUtils::Embed kit from CPAN and run `make test'. If the\ntests pass, read the pods again and again and again. If they fail,\nsubmit a bug report to <https://github.com/Perl/perl5/issues> with the\noutput of \"make test TESTVERBOSE=1\" along with \"perl -V\".\n\nWhen I tried to run my script, I got this message. What does it mean?\nA complete list of Perl's error messages and warnings with explanatory\ntext can be found in perldiag. You can also use the splain program\n(distributed with Perl) to explain the error messages:\n\nperl program 2>diag.out\nsplain [-v] [-p] diag.out\n\nor change your program to explain the messages for you:\n\nuse diagnostics;\n\nor\n\nuse diagnostics -verbose;\n",
                "subsections": []
            },
            "Found in /usr/share/perl/5.34/pod/perlfaq4.pod": {
                "content": "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?\nFor the long explanation, see David Goldberg's \"What Every Computer\nScientist Should Know About Floating-Point Arithmetic\"\n(<http://web.cse.msu.edu/~cse320/Documents/FloatingPoint.pdf>).\n\nInternally, your computer represents floating-point numbers in binary.\nDigital (as in powers of two) computers cannot store all numbers\nexactly. Some real numbers lose precision in the process. This is a\nproblem with how computers store numbers and affects all computer\nlanguages, not just Perl.\n\nperlnumber shows the gory details of number representations and\nconversions.\n\nTo limit the number of decimal places in your numbers, you can use the\n\"printf\" or \"sprintf\" function. See \"Floating-point Arithmetic\" in\nperlop for more details.\n\nprintf \"%.2f\", 10/3;\n\nmy $number = sprintf \"%.2f\", 10/3;\n\nWhy isn't my octal data interpreted correctly?\n(contributed by brian d foy)\n\nYou're probably trying to convert a string to a number, which Perl only\nconverts as a decimal number. When Perl converts a string to a number,\nit ignores leading spaces and zeroes, then assumes the rest of the\ndigits are in base 10:\n\nmy $string = '0644';\n\nprint $string + 0;  # prints 644\n\nprint $string + 44; # prints 688, certainly not octal!\n\nThis problem usually involves one of the Perl built-ins that has the\nsame name a Unix command that uses octal numbers as arguments on the\ncommand line. In this example, \"chmod\" on the command line knows that\nits first argument is octal because that's what it does:\n\n%prompt> chmod 644 file\n\nIf you want to use the same literal digits (644) in Perl, you have to\ntell Perl to treat them as octal numbers either by prefixing the digits\nwith a 0 or using \"oct\":\n\nchmod(     0644, $filename );  # right, has leading zero\nchmod( oct(644), $filename );  # also correct\n\nThe problem comes in when you take your numbers from something that Perl\nthinks is a string, such as a command line argument in @ARGV:\n\nchmod( $ARGV[0],      $filename );  # wrong, even if \"0644\"\n\nchmod( oct($ARGV[0]), $filename );  # correct, treat string as octal\n\nYou can always check the value you're using by printing it in octal\nnotation to ensure it matches what you think it should be. Print it in\noctal and decimal format:\n\nprintf \"0%o %d\", $number, $number;\n\nDoes Perl have a round() function? What about ceil() and floor()? Trig functions?\nRemember that \"int()\" merely truncates toward 0. For rounding to a\ncertain number of digits, \"sprintf()\" or \"printf()\" is usually the\neasiest route.\n\nprintf(\"%.3f\", 3.1415926535);   # prints 3.142\n\nThe POSIX module (part of the standard Perl distribution) implements\n\"ceil()\", \"floor()\", and a number of other mathematical and\ntrigonometric 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 convert between numeric representations/bases/radixes?\nAs always with Perl there is more than one way to do it. Below are a few\nexamples of approaches to making common conversions between number\nrepresentations. This is intended to be representational rather than\nexhaustive.\n\nSome of the examples later in perlfaq4 use the Bit::Vector module from\nCPAN. The reason you might choose Bit::Vector over the perl built-in\nfunctions is that it works with numbers of ANY size, that it is\noptimized for speed on some operations, and for at least some\nprogrammers the notation might be familiar.\n\nHow do I convert hexadecimal into decimal\nUsing perl's built in conversion of \"0x\" notation:\n\nmy $dec = 0xDEADBEEF;\n\nUsing the \"hex\" function:\n\nmy $dec = hex(\"DEADBEEF\");\n\nUsing \"pack\":\n\nmy $dec = unpack(\"N\", pack(\"H8\", substr(\"0\" x 8 . \"DEADBEEF\", -8)));\n\nUsing the CPAN module \"Bit::Vector\":\n\nuse Bit::Vector;\nmy $vec = Bit::Vector->newHex(32, \"DEADBEEF\");\nmy $dec = $vec->toDec();\n\nHow do I convert from decimal to hexadecimal\nUsing \"sprintf\":\n\nmy $hex = sprintf(\"%X\", 3735928559); # upper case A-F\nmy $hex = sprintf(\"%x\", 3735928559); # lower case a-f\n\nUsing \"unpack\":\n\nmy $hex = unpack(\"H*\", pack(\"N\", 3735928559));\n\nUsing Bit::Vector:\n\nuse Bit::Vector;\nmy $vec = Bit::Vector->newDec(32, -559038737);\nmy $hex = $vec->toHex();\n\nAnd Bit::Vector supports odd bit counts:\n\nuse Bit::Vector;\nmy $vec = Bit::Vector->newDec(33, 3735928559);\n$vec->Resize(32); # suppress leading 0 if unwanted\nmy $hex = $vec->toHex();\n\nHow do I convert from octal to decimal\nUsing Perl's built in conversion of numbers with leading zeros:\n\nmy $dec = 033653337357; # note the leading 0!\n\nUsing the \"oct\" function:\n\nmy $dec = oct(\"33653337357\");\n\nUsing Bit::Vector:\n\nuse Bit::Vector;\nmy $vec = Bit::Vector->new(32);\n$vec->ChunkListStore(3, split(//, reverse \"33653337357\"));\nmy $dec = $vec->toDec();\n\nHow do I convert from decimal to octal\nUsing \"sprintf\":\n\nmy $oct = sprintf(\"%o\", 3735928559);\n\nUsing Bit::Vector:\n\nuse Bit::Vector;\nmy $vec = Bit::Vector->newDec(32, -559038737);\nmy $oct = reverse join('', $vec->ChunkListRead(3));\n\nHow do I convert from binary to decimal\nPerl 5.6 lets you write binary numbers directly with the \"0b\"\nnotation:\n\nmy $number = 0b10110110;\n\nUsing \"oct\":\n\nmy $input = \"10110110\";\nmy $decimal = oct( \"0b$input\" );\n\nUsing \"pack\" and \"ord\":\n\nmy $decimal = ord(pack('B8', '10110110'));\n\nUsing \"pack\" and \"unpack\" for larger strings:\n\nmy $int = unpack(\"N\", pack(\"B32\",\nsubstr(\"0\" x 32 . \"11110101011011011111011101111\", -32)));\nmy $dec = sprintf(\"%d\", $int);\n\n# substr() is used to left-pad a 32-character string with zeros.\n\nUsing Bit::Vector:\n\nmy $vec = Bit::Vector->newBin(32, \"11011110101011011011111011101111\");\nmy $dec = $vec->toDec();\n\nHow do I convert from decimal to binary\nUsing \"sprintf\" (perl 5.6+):\n\nmy $bin = sprintf(\"%b\", 3735928559);\n\nUsing \"unpack\":\n\nmy $bin = unpack(\"B*\", pack(\"N\", 3735928559));\n\nUsing Bit::Vector:\n\nuse Bit::Vector;\nmy $vec = Bit::Vector->newDec(32, -559038737);\nmy $bin = $vec->toBin();\n\nThe remaining transformations (e.g. hex -> oct, bin -> hex, etc.)\nare left as an exercise to the inclined reader.\n\nWhy doesn't & work the way I want it to?\nThe behavior of binary arithmetic operators depends on whether they're\nused on numbers or strings. The operators treat a string as a series of\nbits and work with that (the string \"3\" is the bit pattern 00110011).\nThe operators work with the binary form of a number (the number 3 is\ntreated as the bit pattern 00000011).\n\nSo, saying \"11 & 3\" performs the \"and\" operation on numbers (yielding\n3). Saying \"11\" & \"3\" performs the \"and\" operation on strings (yielding\n\"1\").\n\nMost problems with \"&\" and \"|\" arise because the programmer thinks they\nhave a number but really it's a string or vice versa. To avoid this,\nstringify the arguments explicitly (using \"\" or \"qq()\") or convert them\nto numbers explicitly (using \"0+$arg\"). The rest arise because the\nprogrammer says:\n\nif (\"\\020\\020\" & \"\\101\\101\") {\n# ...\n}\n\nbut a string consisting of two null bytes (the result of \"\"\\020\\020\" &\n\"\\101\\101\"\") is not a false value in Perl. You need:\n\nif ( (\"\\020\\020\" & \"\\101\\101\") !~ /[^\\000]/) {\n# ...\n}\n\nHow do I multiply matrices?\nUse the Math::Matrix or Math::MatrixReal modules (available from CPAN)\nor the PDL extension (also available from CPAN).\n\nHow 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\nWhy aren't my random numbers random?\nIf you're using a version of Perl before 5.004, you must call \"srand\"\nonce at the start of your program to seed the random number generator.\n\nBEGIN { srand() if $] < 5.004 }\n\n5.004 and later automatically call \"srand\" at the beginning. Don't call\n\"srand\" more than once--you make your numbers less random, rather than\nmore.\n\nComputers are good at being predictable and bad at being random (despite\nappearances caused by bugs in your programs :-). The random article in\nthe \"Far More Than You Ever Wanted To Know\" collection in\n<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz>, courtesy of Tom\nPhoenix, talks more about this. John von Neumann said, \"Anyone who\nattempts to generate random numbers by deterministic means is, of\ncourse, living in a state of sin.\"\n\nPerl relies on the underlying system for the implementation of \"rand\"\nand \"srand\"; on some systems, the generated numbers are not random\nenough (especially on Windows : see\n<http://www.perlmonks.org/?nodeid=803632>). Several CPAN modules in the\n\"Math\" namespace implement better pseudorandom generators; see for\nexample Math::Random::MT (\"Mersenne Twister\", fast), or\nMath::TrulyRandom (uses the imperfections in the system's timer to\ngenerate random numbers, which is rather slow). More algorithms for\nrandom numbers are described in \"Numerical Recipes in C\" at\n<http://www.nr.com/>\n\nHow do I get a random number between X and Y?\nTo get a random number between two values, you can use the \"rand()\"\nbuilt-in to get a random number between 0 and 1. From there, you shift\nthat into the range that you want.\n\n\"rand($x)\" returns a number such that \"0 <= rand($x) < $x\". Thus what\nyou want to have perl figure out is a random number in the range from 0\nto the difference between your *X* and *Y*.\n\nThat is, to get a number between 10 and 15, inclusive, you want a random\nnumber between 0 and 5 that you can then add to 10.\n\nmy $number = 10 + int rand( 15-10+1 ); # ( 10,11,12,13,14, or 15 )\n\nHence you derive the following simple function to abstract that. It\nselects a random integer between the two given integers (inclusive). For\nexample: \"randomintbetween(50,120)\".\n\nsub randomintbetween {\nmy($min, $max) = @;\n# Assumes that the two arguments are integers themselves!\nreturn $min if $min == $max;\n($min, $max) = ($max, $min)  if  $min > $max;\nreturn $min + int rand(1 + $max - $min);\n}\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 take a string and turn it into epoch seconds?\nIf it's a regular enough string that it always has the same format, you\ncan split it up and pass the parts to \"timelocal\" in the standard\nTime::Local module. Otherwise, you should look into the Date::Calc,\nDate::Parse, and Date::Manip modules from CPAN.\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\nDoes Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?\n(contributed by brian d foy)\n\nPerl itself never had a Y2K problem, although that never stopped people\nfrom creating Y2K problems on their own. See the documentation for\n\"localtime\" for its proper use.\n\nStarting with Perl 5.12, \"localtime\" and \"gmtime\" can handle dates past\n03:14:08 January 19, 2038, when a 32-bit based time would overflow. You\nstill might get a warning on a 32-bit \"perl\":\n\n% perl5.12 -E 'say scalar localtime( 0x9FFFFFFFFFFF )'\nInteger overflow in hexadecimal number at -e line 1.\nWed Nov  1 19:42:39 5576711\n\nOn a 64-bit \"perl\", you can get even larger dates for those really long\nrunning projects:\n\n% perl5.12 -E 'say scalar gmtime( 0x9FFFFFFFFFFF )'\nThu Nov  2 00:42:39 5576711\n\nYou're still out of luck if you need to keep track of decaying protons\nthough.\n\nHow do I validate input?\n(contributed by brian d foy)\n\nThere are many ways to ensure that values are what you expect or want to\naccept. Besides the specific examples that we cover in the perlfaq, you\ncan also look at the modules with \"Assert\" and \"Validate\" in their\nnames, along with other modules such as Regexp::Common.\n\nSome modules have validation for particular types of input, such as\nBusiness::ISBN, Business::CreditCard, Email::Valid, and\nData::Validate::IP.\n\nHow do I unescape a string?\nIt depends just what you mean by \"escape\". URL escapes are dealt with in\nperlfaq9. Shell escapes with the backslash (\"\\\") character are removed\nwith\n\ns/\\\\(.)/$1/g;\n\nThis won't expand \"\\n\" or \"\\t\" or any other special escapes.\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 reverse a string?\nUse \"reverse()\" in scalar context, as documented in \"reverse\" in\nperlfunc.\n\nmy $reversed = reverse $string;\n\nHow do I expand tabs in a string?\nYou can do it yourself:\n\n1 while $string =~ s/\\t+/' ' x (length($&) * 8 - length($`) % 8)/e;\n\nOr you can just use the Text::Tabs module (part of the standard Perl\ndistribution).\n\nuse Text::Tabs;\nmy @expandedlines = expand(@lineswithtabs);\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 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 do I capitalize all the words on one line?\n(contributed by brian d foy)\n\nDamian Conway's Text::Autoformat handles all of the thinking for you.\n\nuse Text::Autoformat;\nmy $x = \"Dr. Strangelove or: How I Learned to Stop \".\n\"Worrying and Love the Bomb\";\n\nprint $x, \"\\n\";\nfor my $style (qw( sentence title highlight )) {\nprint autoformat($x, { case => $style }), \"\\n\";\n}\n\nHow do you want to capitalize those words?\n\nFRED AND BARNEY'S LODGE        # all uppercase\nFred And Barney's Lodge        # title case\nFred and Barney's Lodge        # highlight case\n\nIt's not as easy a problem as it looks. How many words do you think are\nin there? Wait for it... wait for it.... If you answered 5 you're right.\nPerl words are groups of \"\\w+\", but that's not what you want to\ncapitalize. How is Perl supposed to know not to capitalize that \"s\"\nafter the apostrophe? You could try a regular expression:\n\n$string =~ s/ (\n(^\\w)    #at the beginning of the line\n|      # or\n(\\s\\w)   #preceded by whitespace\n)\n/\\U$1/xg;\n\n$string =~ s/([\\w']+)/\\u\\L$1/g;\n\nNow, what if you don't want to capitalize that \"and\"? Just use\nText::Autoformat and get on with the next problem. :)\n\nHow can I split a [character]-delimited string except when inside [character]?\nSeveral modules can handle this sort of parsing--Text::Balanced,\nText::CSV, Text::CSVXS, and Text::ParseWords, among others.\n\nTake the example case of trying to split a string that is\ncomma-separated into its different fields. You can't use \"split(/,/)\"\nbecause you shouldn't split if the comma is inside quotes. For example,\ntake a data line like this:\n\nSAR001,\"\",\"Cimetrix, Inc\",\"Bob Smith\",\"CAM\",N,8,1,0,7,\"Error, Core Dumped\"\n\nDue to the restriction of the quotes, this is a fairly complex problem.\nThankfully, we have Jeffrey Friedl, author of *Mastering Regular\nExpressions*, to handle these for us. He suggests (assuming your string\nis contained in $text):\n\nmy @new = ();\npush(@new, $+) while $text =~ m{\n\"([^\\\"\\\\]*(?:\\\\.[^\\\"\\\\]*)*)\",? # groups the phrase inside the quotes\n| ([^,]+),?\n| ,\n}gx;\npush(@new, undef) if substr($text,-1,1) eq ',';\n\nIf you want to represent quotation marks inside a\nquotation-mark-delimited field, escape them with backslashes (eg, \"like\n\\\"this\\\"\".\n\nAlternatively, the Text::ParseWords module (part of the standard Perl\ndistribution) lets you say:\n\nuse Text::ParseWords;\n@new = quotewords(\",\", 0, $text);\n\nFor parsing or generating CSV, though, using Text::CSV rather than\nimplementing it yourself is highly recommended; you'll save yourself odd\nbugs popping up later by just using code which has already been tried\nand tested in production for years.\n\nHow do I strip blank space from the beginning/end of a string?\n(contributed by brian d foy)\n\nA substitution can do this for you. For a single line, you want to\nreplace all the leading or trailing whitespace with nothing. You can do\nthat with a pair of substitutions:\n\ns/^\\s+//;\ns/\\s+$//;\n\nYou can also write that as a single substitution, although it turns out\nthe combined statement is slower than the separate ones. That might not\nmatter to you, though:\n\ns/^\\s+|\\s+$//g;\n\nIn this regular expression, the alternation matches either at the\nbeginning or the end of the string since the anchors have a lower\nprecedence than the alternation. With the \"/g\" flag, the substitution\nmakes all possible matches, so it gets both. Remember, the trailing\nnewline matches the \"\\s+\", and the \"$\" anchor can match to the absolute\nend of the string, so the newline disappears too. Just add the newline\nto the output, which has the added benefit of preserving \"blank\"\n(consisting entirely of whitespace) lines which the \"^\\s+\" would remove\nall by itself:\n\nwhile( <> ) {\ns/^\\s+|\\s+$//g;\nprint \"$\\n\";\n}\n\nFor a multi-line string, you can apply the regular expression to each\nlogical line in the string by adding the \"/m\" flag (for \"multi-line\").\nWith the \"/m\" flag, the \"$\" matches *before* an embedded newline, so it\ndoesn't remove it. This pattern still removes the newline at the end of\nthe string:\n\n$string =~ s/^\\s+|\\s+$//gm;\n\nRemember that lines consisting entirely of whitespace will disappear,\nsince the first part of the alternation can match the entire string and\nreplace it with nothing. If you need to keep embedded blank lines, you\nhave to do a little more work. Instead of matching any whitespace (since\nthat includes a newline), just match the other whitespace:\n\n$string =~ s/^[\\t\\f ]+|[\\t\\f ]+$//mg;\n\nHow do I pad a string with blanks or pad a number with zeroes?\nIn the following examples, $padlen is the length to which you wish to\npad the string, $text or $num contains the string to be padded, and\n$padchar contains the padding character. You can use a single character\nstring constant instead of the $padchar variable if you know what it is\nin advance. And in the same way you can use an integer in place of\n$padlen if you know the pad length in advance.\n\nThe simplest method uses the \"sprintf\" function. It can pad on the left\nor right with blanks and on the left with zeroes and it will not\ntruncate the result. The \"pack\" function can only pad strings on the\nright with blanks and it will truncate the result to a maximum length of\n$padlen.\n\n# Left padding a string with blanks (no truncation):\nmy $padded = sprintf(\"%${padlen}s\", $text);\nmy $padded = sprintf(\"%*s\", $padlen, $text);  # same thing\n\n# Right padding a string with blanks (no truncation):\nmy $padded = sprintf(\"%-${padlen}s\", $text);\nmy $padded = sprintf(\"%-*s\", $padlen, $text); # same thing\n\n# Left padding a number with 0 (no truncation):\nmy $padded = sprintf(\"%0${padlen}d\", $num);\nmy $padded = sprintf(\"%0*d\", $padlen, $num); # same thing\n\n# Right padding a string with blanks using pack (will truncate):\nmy $padded = pack(\"A$padlen\",$text);\n\nIf you need to pad with a character other than blank or zero you can use\none of the following methods. They all generate a pad string with the\n\"x\" operator and combine that with $text. These methods do not truncate\n$text.\n\nLeft and right padding with any character, creating a new string:\n\nmy $padded = $padchar x ( $padlen - length( $text ) ) . $text;\nmy $padded = $text . $padchar x ( $padlen - length( $text ) );\n\nLeft and right padding with any character, modifying $text directly:\n\nsubstr( $text, 0, 0 ) = $padchar x ( $padlen - length( $text ) );\n$text .= $padchar x ( $padlen - length( $text ) );\n\nHow do I extract selected columns from a string?\n(contributed by brian d foy)\n\nIf you know the columns that contain the data, you can use \"substr\" to\nextract a single column.\n\nmy $column = substr( $line, $startcolumn, $length );\n\nYou can use \"split\" if the columns are separated by whitespace or some\nother delimiter, as long as whitespace or the delimiter cannot appear as\npart of the data.\n\nmy $line    = ' fred barney   betty   ';\nmy @columns = split /\\s+/, $line;\n# ( '', 'fred', 'barney', 'betty' );\n\nmy $line    = 'fred||barney||betty';\nmy @columns = split /\\|/, $line;\n# ( 'fred', '', 'barney', '', 'betty' );\n\nIf you want to work with comma-separated values, don't do this since\nthat format is a bit more complicated. Use one of the modules that\nhandle that format, such as Text::CSV, Text::CSVXS, or Text::CSVPP.\n\nIf you want to break apart an entire line of fixed columns, you can use\n\"unpack\" with the A (ASCII) format. By using a number after the format\nspecifier, you can denote the column width. See the \"pack\" and \"unpack\"\nentries in perlfunc for more details.\n\nmy @fields = unpack( $line, \"A8 A8 A8 A16 A4\" );\n\nNote that spaces in the format argument to \"unpack\" do not denote\nliteral spaces. If you have space separated data, you may want \"split\"\ninstead.\n\nHow do I find the soundex value of a string?\n(contributed by brian d foy)\n\nYou can use the \"Text::Soundex\" module. If you want to do fuzzy or close\nmatching, you might also try the String::Approx, and Text::Metaphone,\nand Text::DoubleMetaphone modules.\n\nHow can I expand variables in text strings?\n(contributed by brian d foy)\n\nIf you can avoid it, don't, or if you can use a templating system, such\nas Text::Template or Template Toolkit, do that instead. You might even\nbe able to get the job done with \"sprintf\" or \"printf\":\n\nmy $string = sprintf 'Say hello to %s and %s', $foo, $bar;\n\nHowever, for the one-off simple case where I don't want to pull out a\nfull templating system, I'll use a string that has two Perl scalar\nvariables in it. In this example, I want to expand $foo and $bar to\ntheir variable's values:\n\nmy $foo = 'Fred';\nmy $bar = 'Barney';\n$string = 'Say hello to $foo and $bar';\n\nOne way I can do this involves the substitution operator and a double\n\"/e\" flag. The first \"/e\" evaluates $1 on the replacement side and turns\nit into $foo. The second /e starts with $foo and replaces it with its\nvalue. $foo, then, turns into 'Fred', and that's finally what's left in\nthe string:\n\n$string =~ s/(\\$\\w+)/$1/eeg; # 'Say hello to Fred and Barney'\n\nThe \"/e\" will also silently ignore violations of strict, replacing\nundefined variable names with the empty string. Since I'm using the \"/e\"\nflag (twice even!), I have all of the same security problems I have with\n\"eval\" in its string form. If there's something odd in $foo, perhaps\nsomething like \"@{[ system \"rm -rf /\" ]}\", then I could get myself in\ntrouble.\n\nTo get around the security problem, I could also pull the values from a\nhash instead of evaluating variable names. Using a single \"/e\", I can\ncheck the hash to ensure the value exists, and if it doesn't, I can\nreplace the missing value with a marker, in this case \"???\" to signal\nthat I missed something:\n\nmy $string = 'This has $foo and $bar';\n\nmy %Replacements = (\nfoo  => 'Fred',\n);\n\n# $string =~ s/\\$(\\w+)/$Replacements{$1}/g;\n$string =~ s/\\$(\\w+)/\nexists $Replacements{$1} ? $Replacements{$1} : '???'\n/eg;\n\nprint $string;\n\nDoes Perl have anything like Ruby's #{} or Python's f string?\nUnlike the others, Perl allows you to embed a variable naked in a double\nquoted string, e.g. \"variable $variable\". When there isn't whitespace or\nother non-word characters following the variable name, you can add\nbraces (e.g. \"foo ${foo}bar\") to ensure correct parsing.\n\nAn array can also be embedded directly in a string, and will be expanded\nby default with spaces between the elements. The default LISTSEPARATOR\ncan be changed by assigning a different string to the special variable\n$\", such as \"local $\" = ', ';\".\n\nPerl also supports references within a string providing the equivalent\nof the features in the other two languages.\n\n\"${\\ ... }\" embedded within a string will work for most simple\nstatements such as an object->method call. More complex code can be\nwrapped in a do block \"${\\ do{...} }\".\n\nWhen you want a list to be expanded per $\", use \"@{[ ... ]}\".\n\nuse Time::Piece;\nuse Time::Seconds;\nmy $scalar = 'STRING';\nmy @array = ( 'zorro', 'a', 1, 'B', 3 );\n\n# Print the current date and time and then Tommorrow\nmy $t = Time::Piece->new;\nsay \"Now is: ${\\ $t->cdate() }\";\nsay \"Tomorrow: ${\\ do{ my $T=Time::Piece->new + ONEDAY ; $T->fullday }}\";\n\n# some variables in strings\nsay \"This is some scalar I have $scalar, this is an array @array.\";\nsay \"You can also write it like this ${scalar} @{array}.\";\n\n# Change the $LISTSEPARATOR\nlocal $\" = ':';\nsay \"Set \\$\\\" to delimit with ':' and sort the Array @{[ sort @array ]}\";\n\nYou may also want to look at the module Quote::Code, and templating\ntools such as Template::Toolkit and Mojo::Template.\n\nSee also: \"How can I expand variables in text strings?\" and \"How do I\nexpand function calls in a string?\" in this FAQ.\n\nWhy don't my <<HERE documents work?\nHere documents are found in perlop. Check for these three things:\n\nThere must be no space after the << part.\nThere (probably) should be a semicolon at the end of the opening token\nYou can't (easily) have any space in front of the tag.\nThere needs to be at least a line separator after the end token.\n\nIf you want to indent the text in the here document, you can do this:\n\n# all in one\n(my $VAR = <<HERETARGET) =~ s/^\\s+//gm;\nyour text\ngoes here\nHERETARGET\n\nBut the HERETARGET must still be flush against the margin. If you want\nthat indented also, you'll have to quote in the indentation.\n\n(my $quote = <<'    FINIS') =~ s/^\\s+//gm;\n...we will have peace, when you and all your works have\nperished--and the works of your dark master to whom you\nwould deliver us. You are a liar, Saruman, and a corrupter\nof men's hearts. --Theoden in /usr/src/perl/taint.c\nFINIS\n$quote =~ s/\\s+--/\\n--/;\n\nA nice general-purpose fixer-upper function for indented here documents\nfollows. It expects to be called with a here document as its argument.\nIt looks to see whether each line begins with a common substring, and if\nso, strips that substring off. Otherwise, it takes the amount of leading\nwhitespace found on the first line and removes that much off each\nsubsequent line.\n\nsub fix {\nlocal $ = shift;\nmy ($white, $leader);  # common whitespace and common leading string\nif (/^\\s*(?:([^\\w\\s]+)(\\s*).*\\n)(?:\\s*\\g1\\g2?.*\\n)+$/) {\n($white, $leader) = ($2, quotemeta($1));\n} else {\n($white, $leader) = (/^(\\s+)/, '');\n}\ns/^\\s*?$leader(?:$white)?//gm;\nreturn $;\n}\n\nThis works with leading special strings, dynamically determined:\n\nmy $rememberthemain = fix<<'    MAININTERPRETERLOOP';\n@@@ int\n@@@ runops() {\n@@@     SAVEI32(runlevel);\n@@@     runlevel++;\n@@@     while ( op = (*op->opppaddr)() );\n@@@     TAINTNOT;\n@@@     return 0;\n@@@ }\nMAININTERPRETERLOOP\n\nOr with a fixed amount of leading whitespace, with remaining indentation\ncorrectly preserved:\n\nmy $poem = fix<<EVERONANDON;\nNow far ahead the Road has gone,\nAnd I must follow, if I can,\nPursuing it with eager feet,\nUntil it joins some larger way\nWhere many paths and errands meet.\nAnd whither then? I cannot say.\n--Bilbo in /usr/src/perl/ppctl.c\nEVERONANDON\n\nBeginning with Perl version 5.26, a much simpler and cleaner way to\nwrite indented here documents has been added to the language: the tilde\n(~) modifier. See \"Indented Here-docs\" in perlop for details.\n\nWhat is the difference between a list and an array?\n(contributed by brian d foy)\n\nA list is a fixed collection of scalars. An array is a variable that\nholds a variable collection of scalars. An array can supply its\ncollection for list operations, so list operations also work on arrays:\n\n# slices\n( 'dog', 'cat', 'bird' )[2,3];\n@animals[2,3];\n\n# iteration\nforeach ( qw( dog cat bird ) ) { ... }\nforeach ( @animals ) { ... }\n\nmy @three = grep { length == 3 } qw( dog cat bird );\nmy @three = grep { length == 3 } @animals;\n\n# supply an argument list\nwashanimals( qw( dog cat bird ) );\nwashanimals( @animals );\n\nArray operations, which change the scalars, rearrange them, or add or\nsubtract some scalars, only work on arrays. These can't work on a list,\nwhich is fixed. Array operations include \"shift\", \"unshift\", \"push\",\n\"pop\", and \"splice\".\n\nAn array can also change its length:\n\n$#animals = 1;  # truncate to two elements\n$#animals = 10000; # pre-extend to 10,001 elements\n\nYou can change an array element, but you can't change a list element:\n\n$animals[0] = 'Rottweiler';\nqw( dog cat bird )[0] = 'Rottweiler'; # syntax error!\n\nforeach ( @animals ) {\ns/^d/fr/;  # works fine\n}\n\nforeach ( qw( dog cat bird ) ) {\ns/^d/fr/;  # Error! Modification of read only value!\n}\n\nHowever, if the list element is itself a variable, it appears that you\ncan change a list element. However, the list element is the variable,\nnot the data. You're not changing the list element, but something the\nlist element refers to. The list element itself doesn't change: it's\nstill the same variable.\n\nYou also have to be careful about context. You can assign an array to a\nscalar to get the number of elements in the array. This only works for\narrays, though:\n\nmy $count = @animals;  # only works with arrays\n\nIf you try to do the same thing with what you think is a list, you get a\nquite different result. Although it looks like you have a list on the\nrighthand side, Perl actually sees a bunch of scalars separated by a\ncomma:\n\nmy $scalar = ( 'dog', 'cat', 'bird' );  # $scalar gets bird\n\nSince you're assigning to a scalar, the righthand side is in scalar\ncontext. The comma operator (yes, it's an operator!) in scalar context\nevaluates its lefthand side, throws away the result, and evaluates it's\nrighthand side and returns the result. In effect, that list-lookalike\nassigns to $scalar it's rightmost value. Many people mess this up\nbecause they choose a list-lookalike whose last element is also the\ncount they expect:\n\nmy $scalar = ( 1, 2, 3 );  # $scalar gets 3, accidentally\n\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 can I tell whether a certain element is contained in a list or array?\n(portions of this answer contributed by Anno Siegel and brian d foy)\n\nHearing the word \"in\" is an *in*dication that you probably should have\nused a hash, not a list or array, to store your data. Hashes are\ndesigned to answer this question quickly and efficiently. Arrays aren't.\n\nThat being said, there are several ways to approach this. If you are\ngoing to make this query many times over arbitrary string values, the\nfastest way is probably to invert the original array and maintain a hash\nwhose keys are the first array's values:\n\nmy @blues = qw/azure cerulean teal turquoise lapis-lazuli/;\nmy %isblue = ();\nfor (@blues) { $isblue{$} = 1 }\n\nNow you can check whether $isblue{$somecolor}. It might have been a\ngood idea to keep the blues all in a hash in the first place.\n\nIf the values are all small integers, you could use a simple indexed\narray. This kind of an array will take up less space:\n\nmy @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);\nmy @istinyprime = ();\nfor (@primes) { $istinyprime[$] = 1 }\n# or simply  @istinyprime[@primes] = (1) x @primes;\n\nNow you check whether $istinyprime[$somenumber].\n\nIf the values in question are integers instead of strings, you can save\nquite a lot of space by using bit strings instead:\n\nmy @articles = ( 1..10, 150..2000, 2017 );\nundef $read;\nfor (@articles) { vec($read,$,1) = 1 }\n\nNow check whether \"vec($read,$n,1)\" is true for some $n.\n\nThese methods guarantee fast individual tests but require a\nre-organization of the original list or array. They only pay off if you\nhave to test multiple values against the same array.\n\nIf you are testing only once, the standard module List::Util exports the\nfunction \"any\" for this purpose. It works by stopping once it finds the\nelement. It's written in C for speed, and its Perl equivalent looks like\nthis subroutine:\n\nsub any (&@) {\nmy $code = shift;\nforeach (@) {\nreturn 1 if $code->();\n}\nreturn 0;\n}\n\nIf speed is of little concern, the common idiom uses grep in scalar\ncontext (which returns the number of items that passed its condition) to\ntraverse the entire list. This does have the benefit of telling you how\nmany matches it found, though.\n\nmy $isthere = grep $ eq $whatever, @array;\n\nIf you want to actually extract the matching elements, simply use grep\nin list context.\n\nmy @matches = grep $ eq $whatever, @array;\n\nHow do I 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 test whether two arrays or hashes are equal?\nThe following code works for single-level arrays. It uses a stringwise\ncomparison, and does not distinguish defined versus undefined empty\nstrings. Modify if you have other needs.\n\n$areequal = comparearrays(\\@frogs, \\@toads);\n\nsub comparearrays {\nmy ($first, $second) = @;\nno warnings;  # silence spurious -w undef complaints\nreturn 0 unless @$first == @$second;\nfor (my $i = 0; $i < @$first; $i++) {\nreturn 0 if $first->[$i] ne $second->[$i];\n}\nreturn 1;\n}\n\nFor multilevel structures, you may wish to use an approach more like\nthis one. It uses the CPAN module FreezeThaw:\n\nuse FreezeThaw qw(cmpStr);\nmy @a = my @b = ( \"this\", \"that\", [ \"more\", \"stuff\" ] );\n\nprintf \"a and b contain %s arrays\\n\",\ncmpStr(\\@a, \\@b) == 0\n? \"the same\"\n: \"different\";\n\nThis approach also works for comparing hashes. Here we'll demonstrate\ntwo different answers:\n\nuse FreezeThaw qw(cmpStr cmpStrHard);\n\nmy %a = my %b = ( \"this\" => \"that\", \"extra\" => [ \"more\", \"stuff\" ] );\n$a{EXTRA} = \\%b;\n$b{EXTRA} = \\%a;\n\nprintf \"a and b contain %s hashes\\n\",\ncmpStr(\\%a, \\%b) == 0 ? \"the same\" : \"different\";\n\nprintf \"a and b contain %s hashes\\n\",\ncmpStrHard(\\%a, \\%b) == 0 ? \"the same\" : \"different\";\n\nThe first reports that both those the hashes contain the same data,\nwhile the second reports that they do not. Which you prefer is left as\nan exercise to the reader.\n\nHow do I find the first array element for which a condition is true?\nTo find the first array element which satisfies a condition, you can use\nthe \"first()\" function in the List::Util module, which comes with Perl\n5.8. This example finds the first element that contains \"Perl\".\n\nuse List::Util qw(first);\n\nmy $element = first { /Perl/ } @array;\n\nIf you cannot use List::Util, you can make your own loop to do the same\nthing. Once you find the element, you stop the loop with last.\n\nmy $found;\nforeach ( @array ) {\nif( /Perl/ ) { $found = $; last }\n}\n\nIf you want the array index, use the \"firstidx()\" function from\n\"List::MoreUtils\":\n\nuse List::MoreUtils qw(firstidx);\nmy $index = firstidx { /Perl/ } @array;\n\nOr write it yourself, iterating through the indices and checking the\narray element at each index until you find one that satisfies the\ncondition:\n\nmy( $found, $index ) = ( undef, -1 );\nfor( $i = 0; $i < @array; $i++ ) {\nif( $array[$i] =~ /Perl/ ) {\n$found = $array[$i];\n$index = $i;\nlast;\n}\n}\n\nHow do I handle linked lists?\n(contributed by brian d foy)\n\nPerl's arrays do not have a fixed size, so you don't need linked lists\nif you just want to add or remove items. You can use array operations\nsuch as \"push\", \"pop\", \"shift\", \"unshift\", or \"splice\" to do that.\n\nSometimes, however, linked lists can be useful in situations where you\nwant to \"shard\" an array so you have many small arrays instead of a\nsingle big array. You can keep arrays longer than Perl's largest array\nindex, lock smaller arrays separately in threaded programs, reallocate\nless memory, or quickly insert elements in the middle of the chain.\n\nSteve Lembark goes through the details in his YAPC::NA 2009 talk \"Perly\nLinked Lists\" ( <http://www.slideshare.net/lembark/perly-linked-lists>\n), although you can just use his LinkedList::Single module.\n\nHow do I handle circular lists?\n(contributed by brian d foy)\n\nIf you want to cycle through an array endlessly, you can increment the\nindex modulo the number of elements in the array:\n\nmy @array = qw( a b c );\nmy $i = 0;\n\nwhile( 1 ) {\nprint $array[ $i++ % @array ], \"\\n\";\nlast if $i > 20;\n}\n\nYou can also use Tie::Cycle to use a scalar that always has the next\nelement of the circular array:\n\nuse Tie::Cycle;\n\ntie my $cycle, 'Tie::Cycle', [ qw( FFFFFF 000000 FFFF00 ) ];\n\nprint $cycle; # FFFFFF\nprint $cycle; # 000000\nprint $cycle; # FFFF00\n\nThe Array::Iterator::Circular creates an iterator object for circular\narrays:\n\nuse Array::Iterator::Circular;\n\nmy $coloriterator = Array::Iterator::Circular->new(\nqw(red green blue orange)\n);\n\nforeach ( 1 .. 20 ) {\nprint $coloriterator->next, \"\\n\";\n}\n\nHow do I shuffle an array randomly?\nIf you either have Perl 5.8.0 or later installed, or if you have\nScalar-List-Utils 1.03 or later installed, you can say:\n\nuse List::Util 'shuffle';\n\n@shuffled = shuffle(@list);\n\nIf not, you can use a Fisher-Yates shuffle.\n\nsub fisheryatesshuffle {\nmy $deck = shift;  # $deck is a reference to an array\nreturn unless @$deck; # must not be empty!\n\nmy $i = @$deck;\nwhile (--$i) {\nmy $j = int rand ($i+1);\n@$deck[$i,$j] = @$deck[$j,$i];\n}\n}\n\n# shuffle my mpeg collection\n#\nmy @mpeg = <audio/*/*.mp3>;\nfisheryatesshuffle( \\@mpeg );    # randomize @mpeg in place\nprint @mpeg;\n\nNote that the above implementation shuffles an array in place, unlike\nthe \"List::Util::shuffle()\" which takes a list and returns a new\nshuffled list.\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()\"\nfunction is discussed in Volume 4 (still unpublished) of Knuth's *The\nArt of Computer 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 sort an array by (anything)?\nSupply a comparison function to sort() (described in \"sort\" in\nperlfunc):\n\n@list = sort { $a <=> $b } @list;\n\nThe default sort function is cmp, string comparison, which would sort\n\"(1, 2, 10)\" into \"(1, 10, 2)\". \"<=>\", used above, is the numerical\ncomparison operator.\n\nIf you have a complicated function needed to pull out the part you want\nto sort on, then don't do it inside the sort function. Pull it out\nfirst, because the sort BLOCK can be called many times for the same\nelement. Here's an example of how to pull out the first word after the\nfirst number on each item, and then sort those words case-insensitively.\n\nmy @idx;\nfor (@data) {\nmy $item;\n($item) = /\\d+\\s*(\\S+)/;\npush @idx, uc($item);\n}\nmy @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];\n\nwhich could also be written this way, using a trick that's come to be\nknown as the Schwartzian Transform:\n\nmy @sorted = map  { $->[0] }\nsort { $a->[1] cmp $b->[1] }\nmap  { [ $, uc( (/\\d+\\s*(\\S+)/)[0]) ] } @data;\n\nIf you need to sort on several fields, the following paradigm is useful.\n\nmy @sorted = sort {\nfield1($a) <=> field1($b) ||\nfield2($a) cmp field2($b) ||\nfield3($a) cmp field3($b)\n} @data;\n\nThis can be conveniently combined with precalculation of keys as given\nabove.\n\nSee the sort article in the \"Far More Than You Ever Wanted To Know\"\ncollection in <http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> for more\nabout this approach.\n\nSee also the question later in perlfaq4 on sorting hashes.\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\nHow do I process an entire hash?\n(contributed by brian d foy)\n\nThere are a couple of ways that you can process an entire hash. You can\nget a list of keys, then go through each key, or grab a one key-value\npair at a time.\n\nTo go through all of the keys, use the \"keys\" function. This extracts\nall of the keys of the hash and gives them back to you as a list. You\ncan then get the value through the particular key you're processing:\n\nforeach my $key ( keys %hash ) {\nmy $value = $hash{$key}\n...\n}\n\nOnce you have the list of keys, you can process that list before you\nprocess the hash elements. For instance, you can sort the keys so you\ncan process them in lexical order:\n\nforeach my $key ( sort keys %hash ) {\nmy $value = $hash{$key}\n...\n}\n\nOr, you might want to only process some of the items. If you only want\nto deal with the keys that start with \"text:\", you can select just those\nusing \"grep\":\n\nforeach my $key ( grep /^text:/, keys %hash ) {\nmy $value = $hash{$key}\n...\n}\n\nIf the hash is very large, you might not want to create a long list of\nkeys. To save some memory, you can grab one key-value pair at a time\nusing \"each()\", which returns a pair you haven't seen yet:\n\nwhile( my( $key, $value ) = each( %hash ) ) {\n...\n}\n\nThe \"each\" operator returns the pairs in apparently random order, so if\nordering matters to you, you'll have to stick with the \"keys\" method.\n\nThe \"each()\" operator can be a bit tricky though. You can't add or\ndelete keys of the hash while you're using it without possibly skipping\nor re-processing some pairs after Perl internally rehashes all of the\nelements. Additionally, a hash has only one iterator, so if you mix\n\"keys\", \"values\", or \"each\" on the same hash, you risk resetting the\niterator and messing up your processing. See the \"each\" entry in\nperlfunc for more details.\n\nHow do I merge two hashes?\n(contributed by brian d foy)\n\nBefore you decide to merge two hashes, you have to decide what to do if\nboth hashes contain keys that are the same and if you want to leave the\noriginal hashes as they were.\n\nIf you want to preserve the original hashes, copy one hash (%hash1) to a\nnew hash (%newhash), then add the keys from the other hash (%hash2 to\nthe new hash. Checking that the key already exists in %newhash gives\nyou a chance to decide what to do with the duplicates:\n\nmy %newhash = %hash1; # make a copy; leave %hash1 alone\n\nforeach my $key2 ( keys %hash2 ) {\nif( exists $newhash{$key2} ) {\nwarn \"Key [$key2] is in both hashes!\";\n# handle the duplicate (perhaps only warning)\n...\nnext;\n}\nelse {\n$newhash{$key2} = $hash2{$key2};\n}\n}\n\nIf you don't want to create a new hash, you can still use this looping\ntechnique; just change the %newhash to %hash1.\n\nforeach my $key2 ( keys %hash2 ) {\nif( exists $hash1{$key2} ) {\nwarn \"Key [$key2] is in both hashes!\";\n# handle the duplicate (perhaps only warning)\n...\nnext;\n}\nelse {\n$hash1{$key2} = $hash2{$key2};\n}\n}\n\nIf you don't care that one hash overwrites keys and values from the\nother, you could just use a hash slice to add one hash to another. In\nthis case, values from %hash2 replace values from %hash1 when they have\nkeys in common:\n\n@hash1{ keys %hash2 } = values %hash2;\n\nWhat happens if I add or remove keys from a hash while iterating over it?\n(contributed by brian d foy)\n\nThe easy answer is \"Don't do that!\"\n\nIf you iterate through the hash with each(), you can delete the key most\nrecently returned without worrying about it. If you delete or add other\nkeys, the iterator may skip or double up on them since perl may\nrearrange the hash table. See the entry for \"each()\" in perlfunc.\n\nHow do I look up a hash element by value?\nCreate a reverse hash:\n\nmy %byvalue = reverse %bykey;\nmy $key = $byvalue{$value};\n\nThat's not particularly efficient. It would be more space-efficient to\nuse:\n\nwhile (my ($key, $value) = each %bykey) {\n$byvalue{$value} = $key;\n}\n\nIf your hash could have repeated values, the methods above will only\nfind one of the associated keys. This may or may not worry you. If it\ndoes worry you, you can always reverse the hash into a hash of arrays\ninstead:\n\nwhile (my ($key, $value) = each %bykey) {\npush @{$keylistbyvalue{$value}}, $key;\n}\n\nHow do I sort a hash (optionally by value instead of key)?\n(contributed by brian d foy)\n\nTo sort a hash, start with the keys. In this example, we give the list\nof keys to the sort function which then compares them ASCIIbetically\n(which might be affected by your locale settings). The output list has\nthe keys in ASCIIbetical order. Once we have the keys, we can go through\nthem to create a report which lists the keys in ASCIIbetical order.\n\nmy @keys = sort { $a cmp $b } keys %hash;\n\nforeach my $key ( @keys ) {\nprintf \"%-20s %6d\\n\", $key, $hash{$key};\n}\n\nWe could get more fancy in the \"sort()\" block though. Instead of\ncomparing the keys, we can compute a value with them and use that value\nas the comparison.\n\nFor instance, to make our report order case-insensitive, we use \"lc\" to\nlowercase the keys before comparing them:\n\nmy @keys = sort { lc $a cmp lc $b } keys %hash;\n\nNote: if the computation is expensive or the hash has many elements, you\nmay want to look at the Schwartzian Transform to cache the computation\nresults.\n\nIf we want to sort by the hash value instead, we use the hash key to\nlook it up. We still get out a list of keys, but this time they are\nordered by their value.\n\nmy @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;\n\nFrom there we can get more complex. If the hash values are the same, we\ncan provide a secondary sort on the hash key.\n\nmy @keys = sort {\n$hash{$a} <=> $hash{$b}\nor\n\"\\L$a\" cmp \"\\L$b\"\n} keys %hash;\n\nHow can I always keep my hash sorted?\nYou can look into using the \"DBFile\" module and \"tie()\" using the\n$DBBTREE hash bindings as documented in \"In Memory Databases\" in\nDBFile. The Tie::IxHash module from CPAN might also be instructive.\nAlthough this does keep your hash sorted, you might not like the\nslowdown you suffer from the tie interface. Are you sure you need to do\nthis? :)\n\nWhat's the difference between \"delete\" and \"undef\" with hashes?\nHashes contain pairs of scalars: the first is the key, the second is the\nvalue. The key will be coerced to a string, although the value can be\nany kind of scalar: string, number, or reference. If a key $key is\npresent in %hash, \"exists($hash{$key})\" will return true. The value for\na given 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 do I reset an each() operation part-way through?\n(contributed by brian d foy)\n\nYou can use the \"keys\" or \"values\" functions to reset \"each\". To simply\nreset the iterator used by \"each\" without doing anything else, use one\nof them in void context:\n\nkeys %hash; # resets iterator, nothing else.\nvalues %hash; # resets iterator, nothing else.\n\nSee the documentation for \"each\" in perlfunc.\n\nHow can I store a multidimensional array in a DBM file?\nEither stringify the structure yourself (no fun), or else get the MLDBM\n(which uses Data::Dumper) module from CPAN and layer it on top of either\nDBFile or GDBMFile. You might also try DBM::Deep, but it can be a bit\nslow.\n\nHow can I make my hash remember the order I put elements into it?\nUse the Tie::IxHash from CPAN.\n\nuse Tie::IxHash;\n\ntie my %myhash, 'Tie::IxHash';\n\nfor (my $i=0; $i<20; $i++) {\n$myhash{$i} = 2*$i;\n}\n\nmy @keys = keys %myhash;\n# @keys = (0,1,2,3,...)\n\nWhy does passing a subroutine an undefined element in a hash create it?\n(contributed by brian d foy)\n\nAre you using a really old version of Perl?\n\nNormally, accessing a hash key's value for a nonexistent key will *not*\ncreate the key.\n\nmy %hash  = ();\nmy $value = $hash{ 'foo' };\nprint \"This won't print\\n\" if exists $hash{ 'foo' };\n\nPassing $hash{ 'foo' } to a subroutine used to be a special case,\nthough. Since you could assign directly to $[0], Perl had to be ready\nto make that assignment so it created the hash key ahead of time:\n\nmysub( $hash{ 'foo' } );\nprint \"This will print before 5.004\\n\" if exists $hash{ 'foo' };\n\nsub mysub {\n# $[0] = 'bar'; # create hash key in case you do this\n1;\n}\n\nSince Perl 5.004, however, this situation is a special case and Perl\ncreates the hash key only when you make the assignment:\n\nmysub( $hash{ 'foo' } );\nprint \"This will print, even after 5.004\\n\" if exists $hash{ 'foo' };\n\nsub mysub {\n$[0] = 'bar';\n}\n\nHowever, if you want the old behavior (and think carefully about that\nbecause it's a weird side effect), you can pass a hash slice instead.\nPerl 5.004 didn't make this a special case:\n\nmysub( @hash{ qw/foo/ } );\n\nHow can I 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 handle binary data correctly?\nPerl is binary-clean, so it can handle binary data just fine. On Windows\nor DOS, however, you have to use \"binmode\" for binary files to avoid\nconversions for line endings. In general, you should use \"binmode\" any\ntime you want to work with binary data.\n\nAlso see \"binmode\" in perlfunc or perlopentut.\n\nIf you're concerned about 8-bit textual data then see perllocale. If you\nwant to deal with multibyte characters, however, there are some gotchas.\nSee the section on Regular Expressions.\n\nHow do I determine whether a scalar is a number/whole/integer/float?\nAssuming that you don't care about IEEE notations like \"NaN\" or\n\"Infinity\", you probably just want to use a regular expression (see also\nperlretut and perlre):\n\nuse 5.010;\n\nif ( /\\D/ )\n{ say \"\\thas nondigits\"; }\nif ( /^\\d+\\z/ )\n{ say \"\\tis a whole number\"; }\nif ( /^-?\\d+\\z/ )\n{ say \"\\tis an integer\"; }\nif ( /^[+-]?\\d+\\z/ )\n{ say \"\\tis a +/- integer\"; }\nif ( /^-?(?:\\d+\\.?|\\.\\d)\\d*\\z/ )\n{ say \"\\tis a real number\"; }\nif ( /^[+-]?(?=\\.?\\d)\\d*\\.?\\d*(?:e[+-]?\\d+)?\\z/i )\n{ say \"\\tis a C float\" }\n\nThere are also some commonly used modules for the task. Scalar::Util\n(distributed with 5.8) provides access to perl's internal function\n\"lookslikenumber\" for determining whether a variable looks like a\nnumber. Data::Types exports functions that validate data types using\nboth the above and other regular expressions. Thirdly, there is\nRegexp::Common which has regular expressions to match various types of\nnumbers. Those three modules are available from the CPAN.\n\nIf you're on a POSIX system, Perl supports the \"POSIX::strtod\" function\nfor converting strings to doubles (and also \"POSIX::strtol\" for longs).\nIts semantics are somewhat cumbersome, so here's a \"getnum\" wrapper\nfunction for more convenient access. This function takes a string and\nreturns the number it found, or \"undef\" for input that isn't a C float.\nThe \"isnumeric\" function is a front end to \"getnum\" if you just want to\nsay, \"Is this a float?\"\n\nsub getnum {\nuse POSIX qw(strtod);\nmy $str = shift;\n$str =~ s/^\\s+//;\n$str =~ s/\\s+$//;\n$! = 0;\nmy($num, $unparsed) = strtod($str);\nif (($str eq '') || ($unparsed != 0) || $!) {\nreturn undef;\n}\nelse {\nreturn $num;\n}\n}\n\nsub isnumeric { defined getnum($[0]) }\n\nOr you could check out the String::Scanf module on the CPAN instead.\n\nHow do I keep persistent data across program calls?\nFor some specific applications, you can use one of the DBM modules. See\nAnyDBMFile. More generically, you should consult the FreezeThaw or\nStorable modules from CPAN. Starting from Perl 5.8, Storable is part of\nthe standard distribution. Here's one example using Storable's \"store\"\nand \"retrieve\" functions:\n\nuse Storable;\nstore(\\%hash, \"filename\");\n\n# later on...\n$href = retrieve(\"filename\");        # by ref\n%hash = %{ retrieve(\"filename\") };   # direct to hash\n\nHow do I print out or copy a recursive data structure?\nThe Data::Dumper module on CPAN (or the 5.005 release of Perl) is great\nfor printing out data structures. The Storable module on CPAN (or the\n5.8 release of Perl), provides a function called \"dclone\" that\nrecursively copies its argument.\n\nuse Storable qw(dclone);\n$r2 = dclone($r1);\n\nWhere $r1 can be a reference to any kind of data structure you'd like.\nIt will be deeply copied. Because \"dclone\" takes and returns references,\nyou'd have to add extra punctuation if you had a hash of arrays that you\nwanted to copy.\n\n%newhash = %{ dclone(\\%oldhash) };\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",
                "subsections": []
            },
            "Found in /usr/share/perl/5.34/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 do I make a temporary file name?\nIf you don't need to know the name of the file, you can use \"open()\"\nwith \"undef\" in place of the file name. In Perl 5.8 or later, the\n\"open()\" function 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 output my numbers with commas added?\n(contributed by brian d foy and Benjamin Goldberg)\n\nYou can use Number::Format to separate places in a number. It handles\nlocale information for those of you who want to insert full stops\ninstead (or anything else that they want to use, really).\n\nThis subroutine will add commas to your number:\n\nsub commify {\nlocal $  = shift;\n1 while s/^([-+]?\\d+)(\\d{3})/$1,$2/;\nreturn $;\n}\n\nThis regex from Benjamin Goldberg will add commas to numbers:\n\ns/(^[-+]?\\d+?(?=(?>(?:\\d{3})+)(?!\\d))|\\G\\d{3}(?=\\d))/$1,/g;\n\nIt is easier to see with comments:\n\ns/(\n^[-+]?             # beginning of number.\n\\d+?               # first digits before first comma\n(?=                # followed by, (but not included in the match) :\n(?>(?:\\d{3})+) # some positive multiple of three digits.\n(?!\\d)         # an *exact* multiple, not x * 3 + 1 or whatever.\n)\n|                  # or:\n\\G\\d{3}            # after the last group, get three digits\n(?=\\d)             # but they have to have more digits after them.\n)/$1,/xg;\n\nHow can I translate tildes (~) in a filename?\nUse the <> (\"glob()\") operator, documented in perlfunc. Versions of Perl\nolder than 5.6 require that you have a shell installed that groks\ntildes. Later versions of Perl have this feature built in. The\nFile::KGlob module (available from CPAN) gives more portable glob\nfunctionality.\n\nWithin Perl, you may use this directly:\n\n$filename =~ s{\n^ ~             # find a leading tilde\n(               # save this in $1\n[^/]        # a non-slash character\n*     # repeated 0 or more times (0 means me)\n)\n}{\n$1\n? (getpwnam($1))[7]\n: ( $ENV{HOME} || $ENV{LOGDIR} )\n}ex;\n\nHow come when I open a file read-write it wipes it out?\nBecause you're using something like this, which truncates the file\n*then* gives you read-write access:\n\nopen my $fh, '+>', '/path/name'; # WRONG (almost always)\n\nWhoops. You should instead use this, which will fail if the file doesn't\nexist:\n\nopen my $fh, '+<', '/path/name'; # open for update\n\nUsing \">\" always clobbers or creates. Using \"<\" never does either. The\n\"+\" doesn't change this.\n\nHere are examples of many kinds of file opens. Those using \"sysopen\" all\nassume that you've pulled in the constants from Fcntl:\n\nuse Fcntl;\n\nTo open file for reading:\n\nopen my $fh, '<', $path                               or die $!;\nsysopen my $fh, $path, ORDONLY                       or die $!;\n\nTo open file for writing, create new file if needed or else truncate old\nfile:\n\nopen my $fh, '>', $path                               or die $!;\nsysopen my $fh, $path, OWRONLY|OTRUNC|OCREAT       or die $!;\nsysopen my $fh, $path, OWRONLY|OTRUNC|OCREAT, 0666 or die $!;\n\nTo open file for writing, create new file, file must not exist:\n\nsysopen my $fh, $path, OWRONLY|OEXCL|OCREAT        or die $!;\nsysopen my $fh, $path, OWRONLY|OEXCL|OCREAT, 0666  or die $!;\n\nTo open file for appending, create if necessary:\n\nopen my $fh, '>>', $path                              or die $!;\nsysopen my $fh, $path, OWRONLY|OAPPEND|OCREAT      or die $!;\nsysopen my $fh, $path, OWRONLY|OAPPEND|OCREAT, 0666 or die $!;\n\nTo open file for appending, file must exist:\n\nsysopen my $fh, $path, OWRONLY|OAPPEND              or die $!;\n\nTo open file for update, file must exist:\n\nopen my $fh, '+<', $path                              or die $!;\nsysopen my $fh, $path, ORDWR                         or die $!;\n\nTo open file for update, create file if necessary:\n\nsysopen my $fh, $path, ORDWR|OCREAT                 or die $!;\nsysopen my $fh, $path, ORDWR|OCREAT, 0666           or die $!;\n\nTo open file for update, file must not exist:\n\nsysopen my $fh, $path, ORDWR|OEXCL|OCREAT          or die $!;\nsysopen my $fh, $path, ORDWR|OEXCL|OCREAT, 0666    or die $!;\n\nTo open a file without blocking, creating if necessary:\n\nsysopen my $fh, '/foo/somefile', OWRONLY|ONDELAY|OCREAT\nor die \"can't open /foo/somefile: $!\":\n\nBe warned that neither creation nor deletion of files is guaranteed to\nbe an atomic operation over NFS. That is, two processes might both\nsuccessfully create or unlink the same file! Therefore OEXCL isn't as\nexclusive as you might wish.\n\nSee also perlopentut.\n\nWhy do I sometimes get an \"Argument list too long\" when I use <*>?\nThe \"<>\" operator performs a globbing operation (see above). In Perl\nversions earlier than v5.6.0, the internal glob() operator forks csh(1)\nto do the actual glob expansion, but csh can't handle more than 127\nitems and so gives the error message \"Argument list too long\". People\nwho installed tcsh as csh won't have this problem, but their users may\nbe surprised by it.\n\nTo get around this, either upgrade to Perl v5.6.0 or later, do the glob\nyourself with readdir() and patterns, or use a module like File::Glob,\none that doesn't use the shell to do globbing.\n\nHow can I open a file named with a leading \">\" or trailing blanks?\n(contributed by Brian McCauley)\n\nThe special two-argument form of Perl's open() function ignores trailing\nblanks in filenames and infers the mode from certain leading characters\n(or a trailing \"|\"). In older versions of Perl this was the only version\nof open() and so it is prevalent in old code and books.\n\nUnless you have a particular reason to use the two-argument form you\nshould use the three-argument form of open() which does not treat any\ncharacters in the filename as special.\n\nopen my $fh, \"<\", \"  file  \";  # filename is \"   file   \"\nopen my $fh, \">\", \">file\";     # filename is \">file\"\n\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\nsome systems where this probability is reduced to zero, and this is not\na concern 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\n\"localtime()\", \"gmtime()\", or \"POSIX::strftime()\" to convert this into\nhuman-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",
                "subsections": [
                    {
                        "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\nFor ordinary files you can also use the \"read\" function.\n\nread( $fh, $var, -s $fh );\n\nThat third argument tests the byte size of the data on the $fh\nfilehandle and reads that many bytes into the buffer $var.\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\nfrom the 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\nHow do I traverse a directory tree?\n(contributed by brian d foy)\n\nThe File::Find module, which comes with Perl, does all of the hard work\nto traverse a directory structure. It comes with Perl. You simply call\nthe \"find\" subroutine with a callback subroutine and the directories you\nwant to traverse:\n\nuse File::Find;\n\nfind( \\&wanted, @directories );\n\nsub wanted {\n# full path in $File::Find::name\n# just filename in $\n... do whatever you want to do ...\n}\n\nThe File::Find::Closures, which you can download from CPAN, provides\nmany ready-to-use subroutines that you can use with File::Find.\n\nThe File::Finder, which you can download from CPAN, can help you create\nthe callback subroutine using something closer to the syntax of the\n\"find\" command-line utility:\n\nuse File::Find;\nuse File::Finder;\n\nmy $deepdirs = File::Finder->depth->type('d')->ls->exec('rmdir','{}');\n\nfind( $deepdirs->asoptions, @places );\n\nThe File::Find::Rule module, which you can download from CPAN, has a\nsimilar interface, but does the traversal for you too:\n\nuse File::Find::Rule;\n\nmy @files = File::Find::Rule->file()\n->name( '*.pm' )\n->in( @INC );\n\nHow do I delete a directory tree?\n(contributed by brian d foy)\n\nIf you have an empty directory, you can use Perl's built-in \"rmdir\". If\nthe directory is not empty (so, with files or subdirectories), you\neither have to empty it yourself (a lot of work) or use a module to help\nyou.\n\nThe File::Path module, which comes with Perl, has a \"removetree\" which\ncan take care of all of the hard work for you:\n\nuse File::Path qw(removetree);\n\nremovetree( @directories );\n\nThe File::Path module also has a legacy interface to the older \"rmtree\"\nsubroutine.\n\nHow do I copy an entire directory?\n(contributed by Shlomi Fish)\n\nTo do the equivalent of \"cp -R\" (i.e. copy an entire directory tree\nrecursively) in portable Perl, you'll either need to write something\nyourself or find a good CPAN module such as File::Copy::Recursive.\n"
                    }
                ]
            },
            "Found in /usr/share/perl/5.34/pod/perlfaq6.pod": {
                "content": "How can I hope to use regular expressions without creating illegible and unmaintainable code?\nThree techniques can make regular expressions maintainable and\nunderstandable.\n\nComments Outside the Regex\nDescribe what you're doing and how you're doing it, using normal\nPerl comments.\n\n# turn the line into the first word, a colon, and the\n# number of characters on the rest of the line\ns/^(\\w+)(.*)/ lc($1) . \":\" . length($2) /meg;\n\nComments Inside the Regex\nThe \"/x\" modifier causes whitespace to be ignored in a regex pattern\n(except in a character class and a few other places), and also\nallows you to use normal comments there, too. As you can imagine,\nwhitespace and comments help a lot.\n\n\"/x\" lets you turn this:\n\ns{<(?:[^>'\"]*|\".*?\"|'.*?')+>}{}gs;\n\ninto this:\n\ns{ <                    # opening angle bracket\n(?:                 # Non-backreffing grouping paren\n[^>'\"] *        # 0 or more things that are neither > nor ' nor \"\n|           #    or else\n\".*?\"           # a section between double quotes (stingy match)\n|           #    or else\n'.*?'           # a section between single quotes (stingy match)\n) +                 #   all occurring one or more times\n>                   # closing angle bracket\n}{}gsx;                 # replace with nothing, i.e. delete\n\nIt's still not quite so clear as prose, but it is very useful for\ndescribing the meaning of each part of the pattern.\n\nDifferent Delimiters\nWhile we normally think of patterns as being delimited with \"/\"\ncharacters, they can be delimited by almost any character. perlre\ndescribes this. For example, the \"s///\" above uses braces as\ndelimiters. Selecting another delimiter can avoid quoting the\ndelimiter within the pattern:\n\ns/\\/usr\\/local/\\/usr\\/share/g;    # bad delimiter choice\ns#/usr/local#/usr/share#g;        # better\n\nUsing logically paired delimiters can be even more readable:\n\ns{/usr/local/}{/usr/share}g;      # better still\n\nHow can I pull out lines between two patterns that are themselves on different lines?\nYou can use Perl's somewhat exotic \"..\" operator (documented in perlop):\n\nperl -ne 'print if /START/ .. /END/' file1 file2 ...\n\nIf you wanted text and not lines, you would use\n\nperl -0777 -ne 'print \"$1\\n\" while /START(.*?)END/gs' file1 file2 ...\n\nBut if you want nested occurrences of \"START\" through \"END\", you'll run\nup against the problem described in the question in this section on\nmatching balanced text.\n\nHere's another example of using \"..\":\n\nwhile (<>) {\nmy $inheader =   1  .. /^$/;\nmy $inbody   = /^$/ .. eof;\n# now choose between them\n} continue {\n$. = 0 if eof;    # fix $.\n}\n\nHow do I match XML, HTML, or other nasty, ugly things with a regex?\nDo not use regexes. Use a module and forget about the regular\nexpressions. The XML::LibXML, HTML::TokeParser and HTML::TreeBuilder\nmodules are good starts, although each namespace has other parsing\nmodules specialized for certain tasks and different ways of doing it.\nStart at CPAN Search ( <http://metacpan.org/> ) and wonder at all the\nwork people have done for you already! :)\n\nI put a regular expression into $/ but it didn't work. What's wrong?\n$/ has to be a string. You can use these examples if you really need to\ndo this.\n\nIf you have File::Stream, this is easy.\n\nuse File::Stream;\n\nmy $stream = File::Stream->new(\n$filehandle,\nseparator => qr/\\s*,\\s*/,\n);\n\nprint \"$\\n\" while <$stream>;\n\nIf you don't have File::Stream, you have to do a little more work.\n\nYou can use the four-argument form of sysread to continually add to a\nbuffer. After you add to the buffer, you check if you have a complete\nline (using your regular expression).\n\nlocal $ = \"\";\nwhile( sysread FH, $, 8192, length ) {\nwhile( s/^((?s).*?)yourpattern// ) {\nmy $record = $1;\n# do stuff here.\n}\n}\n\nYou can do the same thing with foreach and a match using the c flag and\nthe \\G anchor, if you do not mind your entire file being in memory at\nthe end.\n\nlocal $ = \"\";\nwhile( sysread FH, $, 8192, length ) {\nforeach my $record ( m/\\G((?s).*?)yourpattern/gc ) {\n# do stuff here.\n}\nsubstr( $, 0, pos ) = \"\" if pos;\n}\n\nHow do I substitute case-insensitively on the LHS while preserving case on the RHS?\nHere's a lovely Perlish solution by Larry Rosler. It exploits properties\nof bitwise xor on ASCII strings.\n\n$= \"this is a TEsT case\";\n\n$old = 'test';\n$new = 'success';\n\ns{(\\Q$old\\E)}\n{ uc $new | (uc $1 ^ $1) .\n(uc(substr $1, -1) ^ substr $1, -1) x\n(length($new) - length $1)\n}egi;\n\nprint;\n\nAnd here it is as a subroutine, modeled after the above:\n\nsub preservecase {\nmy ($old, $new) = @;\nmy $mask = uc $old ^ $old;\n\nuc $new | $mask .\nsubstr($mask, -1) x (length($new) - length($old))\n}\n\n$string = \"this is a TEsT case\";\n$string =~ s/(test)/preservecase($1, \"success\")/egi;\nprint \"$string\\n\";\n\nThis prints:\n\nthis is a SUcCESS case\n\nAs an alternative, to keep the case of the replacement word if it is\nlonger than the original, you can use this code, by Jeff Pinyan:\n\nsub preservecase {\nmy ($from, $to) = @;\nmy ($lf, $lt) = map length, @;\n\nif ($lt < $lf) { $from = substr $from, 0, $lt }\nelse { $from .= substr $to, $lf }\n\nreturn uc $to | ($from ^ uc $from);\n}\n\nThis changes the sentence to \"this is a SUcCess case.\"\n\nJust to show that C programmers can write C in any programming language,\nif you prefer a more C-like solution, the following script makes the\nsubstitution have the same case, letter by letter, as the original. (It\nalso happens to run about 240% slower than the Perlish solution runs.)\nIf the substitution has more characters than the string being\nsubstituted, the case of the last character is used for the rest of the\nsubstitution.\n\n# Original by Nathan Torkington, massaged by Jeffrey Friedl\n#\nsub preservecase\n{\nmy ($old, $new) = @;\nmy $state = 0; # 0 = no change; 1 = lc; 2 = uc\nmy ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));\nmy $len = $oldlen < $newlen ? $oldlen : $newlen;\n\nfor ($i = 0; $i < $len; $i++) {\nif ($c = substr($old, $i, 1), $c =~ /[\\W\\d]/) {\n$state = 0;\n} elsif (lc $c eq $c) {\nsubstr($new, $i, 1) = lc(substr($new, $i, 1));\n$state = 1;\n} else {\nsubstr($new, $i, 1) = uc(substr($new, $i, 1));\n$state = 2;\n}\n}\n# finish up with any remaining new (for when new is longer than old)\nif ($newlen > $oldlen) {\nif ($state == 1) {\nsubstr($new, $oldlen) = lc(substr($new, $oldlen));\n} elsif ($state == 2) {\nsubstr($new, $oldlen) = uc(substr($new, $oldlen));\n}\n}\nreturn $new;\n}\n\nHow do I use a regular expression to strip C-style comments from a file?\nWhile this actually can be done, it's much harder than you'd think. For\nexample, this one-liner\n\nperl -0777 -pe 's{/\\*.*?\\*/}{}gs' foo.c\n\nwill work in many but not all cases. You see, it's too simple-minded for\ncertain kinds of C programs, in particular, those with what appear to be\ncomments in quoted strings. For that, you'd need something like this,\ncreated by Jeffrey Friedl and later modified by Fred Curtis.\n\n$/ = undef;\n$ = <>;\ns#/\\*[^*]*\\*+([^/*][^*]*\\*+)*/|(\"(\\\\.|[^\"\\\\])*\"|'(\\\\.|[^'\\\\])*'|.[^/\"'\\\\]*)#defined $2 ? $2 : \"\"#gse;\nprint;\n\nThis could, of course, be more legibly written with the \"/x\" modifier,\nadding whitespace and comments. Here it is expanded, courtesy of Fred\nCurtis.\n\ns{\n/\\*         ##  Start of /* ... */ comment\n[^*]*\\*+    ##  Non-* followed by 1-or-more *'s\n(\n[^/*][^*]*\\*+\n)*          ##  0-or-more things which don't start with /\n##    but do end with '*'\n/           ##  End of /* ... */ comment\n\n|         ##     OR  various things which aren't comments:\n\n(\n\"           ##  Start of \" ... \" string\n(\n\\\\.           ##  Escaped char\n|               ##    OR\n[^\"\\\\]        ##  Non \"\\\n)*\n\"           ##  End of \" ... \" string\n\n|         ##     OR\n\n'           ##  Start of ' ... ' string\n(\n\\\\.           ##  Escaped char\n|               ##    OR\n[^'\\\\]        ##  Non '\\\n)*\n'           ##  End of ' ... ' string\n\n|         ##     OR\n\n.           ##  Anything other char\n[^/\"'\\\\]*   ##  Chars which doesn't start a comment, string or escape\n)\n}{defined $2 ? $2 : \"\"}gxse;\n\nA slight modification also removes C++ comments, possibly spanning\nmultiple lines using a continuation character:\n\ns#/\\*[^*]*\\*+([^/*][^*]*\\*+)*/|//([^\\\\]|[^\\n][\\n]?)*?\\n|(\"(\\\\.|[^\"\\\\])*\"|'(\\\\.|[^'\\\\])*'|.[^/\"'\\\\]*)#defined $3 ? $3 : \"\"#gse;\n\nCan I use Perl regular expressions to match balanced text?\n(contributed by brian d foy)\n\nYour first try should probably be the Text::Balanced module, which is in\nthe Perl standard library since Perl 5.8. It has a variety of functions\nto deal with tricky text. The Regexp::Common module can also help by\nproviding canned patterns you can use.\n\nAs of Perl 5.10, you can match balanced text with regular expressions\nusing recursive patterns. Before Perl 5.10, you had to resort to various\ntricks such as using Perl code in \"(??{})\" sequences.\n\nHere's an example using a recursive regular expression. The goal is to\ncapture all of the text within angle brackets, including the text in\nnested angle brackets. This sample text has two \"major\" groups: a group\nwith one level of nesting and a group with two levels of nesting. There\nare five total groups in angle brackets:\n\nI have some <brackets in <nested brackets> > and\n<another group <nested once <nested twice> > >\nand that's it.\n\nThe regular expression to match the balanced text uses two new (to Perl\n5.10) regular expression features. These are covered in perlre and this\nexample is a modified version of one in that documentation.\n\nFirst, adding the new possessive \"+\" to any quantifier finds the longest\nmatch and does not backtrack. That's important since you want to handle\nany angle brackets through the recursion, not backtracking. The group\n\"[^<>]++\" finds one or more non-angle brackets without backtracking.\n\nSecond, the new \"(?PARNO)\" refers to the sub-pattern in the particular\ncapture group given by \"PARNO\". In the following regex, the first\ncapture group finds (and remembers) the balanced text, and you need that\nsame pattern within the first buffer to get past the nested text. That's\nthe recursive part. The \"(?1)\" uses the pattern in the outer capture\ngroup as an independent part of the regex.\n\nPutting it all together, you have:\n\n#!/usr/local/bin/perl5.10.0\n\nmy $string =<<\"HERE\";\nI have some <brackets in <nested brackets> > and\n<another group <nested once <nested twice> > >\nand that's it.\nHERE\n\nmy @groups = $string =~ m/\n(                   # start of capture group 1\n<                   # match an opening angle bracket\n(?:\n[^<>]++     # one or more non angle brackets, non backtracking\n|\n(?1)        # found < or >, so recurse to capture group 1\n)*\n>                   # match a closing angle bracket\n)                   # end of capture group 1\n/xg;\n\n$\" = \"\\n\\t\";\nprint \"Found:\\n\\t@groups\\n\";\n\nThe output shows that Perl found the two major groups:\n\nFound:\n<brackets in <nested brackets> >\n<another group <nested once <nested twice> > >\n\nWith a little extra work, you can get all of the groups in angle\nbrackets even if they are in other angle brackets too. Each time you get\na balanced match, remove its outer delimiter (that's the one you just\nmatched so don't match it again) and add it to a queue of strings to\nprocess. Keep doing that until you get no matches:\n\n#!/usr/local/bin/perl5.10.0\n\nmy @queue =<<\"HERE\";\nI have some <brackets in <nested brackets> > and\n<another group <nested once <nested twice> > >\nand that's it.\nHERE\n\nmy $regex = qr/\n(                   # start of bracket 1\n<                   # match an opening angle bracket\n(?:\n[^<>]++     # one or more non angle brackets, non backtracking\n|\n(?1)        # recurse to bracket 1\n)*\n>                   # match a closing angle bracket\n)                   # end of bracket 1\n/x;\n\n$\" = \"\\n\\t\";\n\nwhile( @queue ) {\nmy $string = shift @queue;\n\nmy @groups = $string =~ m/$regex/g;\nprint \"Found:\\n\\t@groups\\n\\n\" if @groups;\n\nunshift @queue, map { s/^<//; s/>$//; $ } @groups;\n}\n\nThe output shows all of the groups. The outermost matches show up first\nand the nested matches show up later:\n\nFound:\n<brackets in <nested brackets> >\n<another group <nested once <nested twice> > >\n\nFound:\n<nested brackets>\n\nFound:\n<nested once <nested twice> >\n\nFound:\n<nested twice>\n\nWhat does it mean that regexes are greedy? How can I get around it?\nMost people mean that greedy regexes match as much as they can.\nTechnically speaking, it's actually the quantifiers (\"?\", \"*\", \"+\",\n\"{}\") that are greedy rather than the whole pattern; Perl prefers local\ngreed and immediate gratification to overall greed. To get non-greedy\nversions of the same quantifiers, use (\"??\", \"*?\", \"+?\", \"{}?\").\n\nAn example:\n\nmy $s1 = my $s2 = \"I am very very cold\";\n$s1 =~ s/ve.*y //;      # I am cold\n$s2 =~ s/ve.*?y //;     # I am very cold\n\nNotice how the second substitution stopped matching as soon as it\nencountered \"y \". The \"*?\" quantifier effectively tells the regular\nexpression engine to find a match as quickly as possible and pass\ncontrol on to whatever is next in line, as you would if you were playing\nhot potato.\n\nHow do I process each word on each line?\nUse the split function:\n\nwhile (<>) {\nforeach my $word ( split ) {\n# do something with $word here\n}\n}\n\nNote that this isn't really a word in the English sense; it's just\nchunks of consecutive non-whitespace characters.\n\nTo work with only alphanumeric sequences (including underscores), you\nmight consider\n\nwhile (<>) {\nforeach $word (m/(\\w+)/g) {\n# do something with $word here\n}\n}\n\nHow can I print out a word-frequency or line-frequency summary?\nTo do this, you have to parse out each word in the input stream. We'll\npretend that by word you mean chunk of alphabetics, hyphens, or\napostrophes, rather than the non-whitespace chunk idea of a word given\nin the previous question:\n\nmy (%seen);\nwhile (<>) {\nwhile ( /(\\b[^\\W\\d][\\w'-]+\\b)/g ) {   # misses \"`sheep'\"\n$seen{$1}++;\n}\n}\n\nwhile ( my ($word, $count) = each %seen ) {\nprint \"$count $word\\n\";\n}\n\nIf you wanted to do the same thing for lines, you wouldn't need a\nregular expression:\n\nmy (%seen);\n\nwhile (<>) {\n$seen{$}++;\n}\n\nwhile ( my ($line, $count) = each %seen ) {\nprint \"$count $line\";\n}\n\nIf you want these output in a sorted order, see perlfaq4: \"How do I sort\na hash (optionally by value instead of key)?\".\n\nHow can I do approximate matching?\nSee the module String::Approx available from CPAN.\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\nWhy does using $&, $`, or $' slow my program down?\n(contributed by Anno Siegel)\n\nOnce Perl sees that you need one of these variables anywhere in the\nprogram, it provides them on each and every pattern match. That means\nthat on every pattern match the entire string will be copied, part of it\nto $`, part to $&, and part to $'. Thus the penalty is most severe with\nlong strings and patterns that match often. Avoid $&, $', and $` if you\ncan, but if you can't, once you've used them at all, use them at will\nbecause you've already paid the price. Remember that some algorithms\nreally appreciate them. As of the 5.005 release, the $& variable is no\nlonger \"expensive\" the way the other two are.\n\nSince Perl 5.6.1 the special variables @- and @+ can functionally\nreplace $`, $& and $'. These arrays contain pointers to the beginning\nand end of each match (see perlvar for the full story), so they give you\nessentially the same information, but without the risk of excessive\nstring copying.\n\nPerl 5.10 added three specials, \"${^MATCH}\", \"${^PREMATCH}\", and\n\"${^POSTMATCH}\" to do the same job but without the global performance\npenalty. Perl 5.10 only sets these variables if you compile or execute\nthe regular expression with the \"/p\" modifier.\n\nWhat good is \"\\G\" in a regular expression?\nYou use the \"\\G\" anchor to start the next match on the same string where\nthe last match left off. The regular expression engine cannot skip over\nany characters to find the next match with this anchor, so \"\\G\" is\nsimilar to the beginning of string anchor, \"^\". The \"\\G\" anchor is\ntypically used with the \"g\" modifier. It uses the value of \"pos()\" as\nthe position to start the next match. As the match operator makes\nsuccessive matches, it updates \"pos()\" with the position of the next\ncharacter past the last match (or the first character of the next match,\ndepending on how you like to look at it). Each string has its own\n\"pos()\" value.\n\nSuppose you want to match all of consecutive pairs of digits in a string\nlike \"1122a44\" and stop matching when you encounter non-digits. You want\nto match 11 and 22 but the letter \"a\" shows up between 22 and 44 and you\nwant to stop at \"a\". Simply matching pairs of digits skips over the \"a\"\nand still matches 44.\n\n$ = \"1122a44\";\nmy @pairs = m/(\\d\\d)/g;   # qw( 11 22 44 )\n\nIf you use the \"\\G\" anchor, you force the match after 22 to start with\nthe \"a\". The regular expression cannot match there since it does not\nfind a digit, so the next match fails and the match operator returns the\npairs it already found.\n\n$ = \"1122a44\";\nmy @pairs = m/\\G(\\d\\d)/g; # qw( 11 22 )\n\nYou can also use the \"\\G\" anchor in scalar context. You still need the\n\"g\" modifier.\n\n$ = \"1122a44\";\nwhile( m/\\G(\\d\\d)/g ) {\nprint \"Found $1\\n\";\n}\n\nAfter the match fails at the letter \"a\", perl resets \"pos()\" and the\nnext match on the same string starts at the beginning.\n\n$ = \"1122a44\";\nwhile( m/\\G(\\d\\d)/g ) {\nprint \"Found $1\\n\";\n}\n\nprint \"Found $1 after while\" if m/(\\d\\d)/g; # finds \"11\"\n\nYou can disable \"pos()\" resets on fail with the \"c\" modifier, documented\nin perlop and perlreref. Subsequent matches start where the last\nsuccessful match ended (the value of \"pos()\") even if a match on the\nsame string has failed in the meantime. In this case, the match after\nthe \"while()\" loop starts at the \"a\" (where the last match stopped), and\nsince it does not use any anchor it can skip over the \"a\" to find 44.\n\n$ = \"1122a44\";\nwhile( m/\\G(\\d\\d)/gc ) {\nprint \"Found $1\\n\";\n}\n\nprint \"Found $1 after while\" if m/(\\d\\d)/g; # finds \"44\"\n\nTypically you use the \"\\G\" anchor with the \"c\" modifier when you want to\ntry a different match if one fails, such as in a tokenizer. Jeffrey\nFriedl offers this example which works in 5.004 or later.\n\nwhile (<>) {\nchomp;\nPARSER: {\nm/ \\G( \\d+\\b    )/gcx   && do { print \"number: $1\\n\";  redo; };\nm/ \\G( \\w+      )/gcx   && do { print \"word:   $1\\n\";  redo; };\nm/ \\G( \\s+      )/gcx   && do { print \"space:  $1\\n\";  redo; };\nm/ \\G( [^\\w\\d]+ )/gcx   && do { print \"other:  $1\\n\";  redo; };\n}\n}\n\nFor each line, the \"PARSER\" loop first tries to match a series of digits\nfollowed by a word boundary. This match has to start at the place the\nlast match left off (or the beginning of the string on the first match).\nSince \"m/ \\G( \\d+\\b )/gcx\" uses the \"c\" modifier, if the string does not\nmatch that regular expression, perl does not reset pos() and the next\nmatch starts at the same position to try a different pattern.\n\nAre Perl regexes DFAs or NFAs? Are they POSIX compliant?\nWhile it's true that Perl's regular expressions resemble the DFAs\n(deterministic finite automata) of the egrep(1) program, they are in\nfact implemented as NFAs (non-deterministic finite automata) to allow\nbacktracking and backreferencing. And they aren't POSIX-style either,\nbecause those guarantee worst-case behavior for all cases. (It seems\nthat some people prefer guarantees of consistency, even when what's\nguaranteed is slowness.) See the book \"Mastering Regular Expressions\"\n(from O'Reilly) by Jeffrey Friedl for all the details you could ever\nhope to know on these matters (a full citation appears in perlfaq2).\n\nWhat's wrong with using grep in a void context?\nThe problem is that grep builds a return list, regardless of the\ncontext. This means you're making Perl go to the trouble of building a\nlist that you then just throw away. If the list is large, you waste both\ntime and space. If your intent is to iterate over the list, then use a\nfor loop for this purpose.\n\nIn perls older than 5.8.1, map suffers from this problem as well. But\nsince 5.8.1, this has been fixed, and map is context aware - in void\ncontext, no lists are constructed.\n\nHow do I match a regular expression that's in a variable?\n(contributed by brian d foy)\n\nWe don't have to hard-code patterns into the match operator (or anything\nelse that works with regular expressions). We can put the pattern in a\nvariable for later use.\n\nThe match operator is a double quote context, so you can interpolate\nyour variable just like a double quoted string. In this case, you read\nthe regular expression as user input and store it in $regex. Once you\nhave the pattern in $regex, you use that variable in the match operator.\n\nchomp( my $regex = <STDIN> );\n\nif( $string =~ m/$regex/ ) { ... }\n\nAny regular expression special characters in $regex are still special,\nand the pattern still has to be valid or Perl will complain. For\ninstance, in this pattern there is an unpaired parenthesis.\n\nmy $regex = \"Unmatched ( paren\";\n\n\"Two parens to bind them all\" =~ m/$regex/;\n\nWhen Perl compiles the regular expression, it treats the parenthesis as\nthe start of a memory match. When it doesn't find the closing\nparenthesis, it complains:\n\nUnmatched ( in regex; marked by <-- HERE in m/Unmatched ( <-- HERE  paren/ at script line 3.\n\nYou can get around this in several ways depending on our situation.\nFirst, if you don't want any of the characters in the string to be\nspecial, you can escape them with \"quotemeta\" before you use the string.\n\nchomp( my $regex = <STDIN> );\n$regex = quotemeta( $regex );\n\nif( $string =~ m/$regex/ ) { ... }\n\nYou can also do this directly in the match operator using the \"\\Q\" and\n\"\\E\" sequences. The \"\\Q\" tells Perl where to start escaping special\ncharacters, and the \"\\E\" tells it where to stop (see perlop for more\ndetails).\n\nchomp( my $regex = <STDIN> );\n\nif( $string =~ m/\\Q$regex\\E/ ) { ... }\n\nAlternately, you can use \"qr//\", the regular expression quote operator\n(see perlop for more details). It quotes and perhaps compiles the\npattern, and you can apply regular expression flags to the pattern.\n\nchomp( my $input = <STDIN> );\n\nmy $regex = qr/$input/is;\n\n$string =~ m/$regex/  # same as m/$input/is;\n\nYou might also want to trap any errors by wrapping an \"eval\" block\naround the whole thing.\n\nchomp( my $input = <STDIN> );\n\neval {\nif( $string =~ m/\\Q$input\\E/ ) { ... }\n};\nwarn $@ if $@;\n\nOr...\n\nmy $regex = eval { qr/$input/is };\nif( defined $regex ) {\n$string =~ m/$regex/;\n}\nelse {\nwarn $@;\n}\n",
                "subsections": []
            },
            "Found in /usr/share/perl/5.34/pod/perlfaq7.pod": {
                "content": "What are all these $@%&* punctuation signs, and how do I know when to use them?\nThey are type specifiers, as detailed in perldata:\n\n$ for scalar values (number, string or reference)\n@ for arrays\n% for hashes (associative arrays)\n& for subroutines (aka functions, procedures, methods)\n* for all types of that symbol name. In version 4 you used them like\npointers, but in modern perls you can just use references.\n\nThere are a couple of other symbols that you're likely to encounter that\naren't really type specifiers:\n\n<> are used for inputting a record from a filehandle.\n\\  takes a reference to something.\n\nNote that <FILE> is *neither* the type specifier for files nor the name\nof the handle. It is the \"<>\" operator applied to the handle FILE. It\nreads one line (well, record--see \"$/\" in perlvar) from the handle FILE\nin scalar context, or *all* lines in list context. When performing open,\nclose, or any other operation besides \"<>\" on files, or even when\ntalking about the handle, do *not* use the brackets. These are correct:\n\"eof(FH)\", \"seek(FH, 0, 2)\" and \"copying from STDIN to FILE\".\n\nDo I always/never have to quote my strings or use semicolons and commas?\nNormally, a bareword doesn't need to be quoted, but in most cases\nprobably should be (and must be under \"use strict\"). But a hash key\nconsisting of a simple word and the left-hand operand to the \"=>\"\noperator both count as though they were quoted:\n\nThis                    is like this\n------------            ---------------\n$foo{line}              $foo{'line'}\nbar => stuff            'bar' => stuff\n\nThe final semicolon in a block is optional, as is the final comma in a\nlist. Good style (see perlstyle) says to put them in except for\none-liners:\n\nif ($whoops) { exit 1 }\nmy @nums = (1, 2, 3);\n\nif ($whoops) {\nexit 1;\n}\n\nmy @lines = (\n\"There Beren came from mountains cold\",\n\"And lost he wandered under leaves\",\n);\n\nHow do I skip some return values?\nOne way is to treat the return values as a list and index into it:\n\n$dir = (getpwnam($user))[7];\n\nAnother way is to use undef as an element on the left-hand-side:\n\n($dev, $ino, undef, undef, $uid, $gid) = stat($file);\n\nYou can also use a list slice to select only the elements that you need:\n\n($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5];\n\nHow do I temporarily block warnings?\nIf you are running Perl 5.6.0 or better, the \"use warnings\" pragma\nallows fine control of what warnings are produced. See perllexwarn for\nmore details.\n\n{\nno warnings;          # temporarily turn off warnings\n$x = $y + $z;         # I know these might be undef\n}\n\nAdditionally, you can enable and disable categories of warnings. You\nturn off the categories you want to ignore and you can still get other\ncategories of warnings. See perllexwarn for the complete details,\nincluding the category names and hierarchy.\n\n{\nno warnings 'uninitialized';\n$x = $y + $z;\n}\n\nIf you have an older version of Perl, the $^W variable (documented in\nperlvar) controls runtime warnings for a block:\n\n{\nlocal $^W = 0;        # temporarily turn off warnings\n$x = $y + $z;         # I know these might be undef\n}\n\nNote that like all the punctuation variables, you cannot currently use",
                "subsections": [
                    {
                        "name": "my",
                        "content": "Why do Perl operators have different precedence than C operators?\nActually, they don't. All C operators that Perl copies have the same\nprecedence in Perl as they do in C. The problem is with operators that C\ndoesn't have, especially functions that give a list context to\neverything on their right, eg. print, chmod, exec, and so on. Such\nfunctions are called \"list operators\" and appear as such in the\nprecedence table in perlop.\n\nA common mistake is to write:\n\nunlink $file || die \"snafu\";\n\nThis gets interpreted as:\n\nunlink ($file || die \"snafu\");\n\nTo avoid this problem, either put in extra parentheses or use the super\nlow precedence \"or\" operator:\n\n(unlink $file) || die \"snafu\";\nunlink $file or die \"snafu\";\n\nThe \"English\" operators (\"and\", \"or\", \"xor\", and \"not\") deliberately\nhave precedence lower than that of list operators for just such\nsituations as the one above.\n\nAnother operator with surprising precedence is exponentiation. It binds\nmore tightly even than unary minus, making \"-22\" produce a negative\nfour and not a positive one. It is also right-associating, meaning that\n\"232\" is two raised to the ninth power, not eight squared.\n\nAlthough it has the same precedence as in C, Perl's \"?:\" operator\nproduces an lvalue. This assigns $x to either $iftrue or $iffalse,\ndepending on the trueness of $maybe:\n\n($maybe ? $iftrue : $iffalse) = $x;\n\nHow do I declare/create a structure?\nIn general, you don't \"declare\" a structure. Just use a (probably\nanonymous) hash reference. See perlref and perldsc for details. Here's\nan example:\n\n$person = {};                   # new anonymous hash\n$person->{AGE}  = 24;           # set field AGE to 24\n$person->{NAME} = \"Nat\";        # set field NAME to \"Nat\"\n\nIf you're looking for something a bit more rigorous, try perlootut.\n\nHow do I create a module?\nperlnewmod is a good place to start, ignore the bits about uploading to\nCPAN if you don't want to make your module publicly available.\n\nExtUtils::ModuleMaker and Module::Starter are also good places to start.\nMany CPAN authors now use Dist::Zilla to automate as much as possible.\n\nDetailed documentation about modules can be found at: perlmod,\nperlmodlib, perlmodstyle.\n\nIf you need to include C code or C library interfaces use h2xs. h2xs\nwill create the module distribution structure and the initial interface\nfiles. perlxs and perlxstut explain the details.\n\nHow do I adopt or take over a module already on CPAN?\nAsk the current maintainer to make you a co-maintainer or transfer the\nmodule to you.\n\nIf you can not reach the author for some reason contact the PAUSE admins\nat modules@perl.org who may be able to help, but each case is treated\nseparately.\n\n*   Get a login for the Perl Authors Upload Server (PAUSE) if you don't\nalready have one: <http://pause.perl.org>\n\n*   Write to modules@perl.org explaining what you did to contact the\ncurrent maintainer. The PAUSE admins will also try to reach the\nmaintainer.\n\n*   Post a public message in a heavily trafficked site announcing your\nintention to take over the module.\n\n*   Wait a bit. The PAUSE admins don't want to act too quickly in case\nthe current maintainer is on holiday. If there's no response to\nprivate communication or the public post, a PAUSE admin can transfer\nit to you.\n\nHow do I create a class?\n(contributed by brian d foy)\n\nIn Perl, a class is just a package, and methods are just subroutines.\nPerl doesn't get more formal than that and lets you set up the package\njust the way that you like it (that is, it doesn't set up anything for\nyou).\n\nSee also perlootut, a tutorial that covers class creation, and perlobj.\n\nHow can I tell if a variable is tainted?\nYou can use the tainted() function of the Scalar::Util module, available\nfrom CPAN (or included with Perl since release 5.8.0). See also\n\"Laundering and Detecting Tainted Data\" in perlsec.\n\nWhat is variable suicide and how can I prevent it?\nThis problem was fixed in perl 5.00405, so preventing it means\nupgrading your version of perl. ;)\n\nVariable suicide is when you (temporarily or permanently) lose the value\nof a variable. It is caused by scoping through my() and local()\ninteracting with either closures or aliased foreach() iterator variables\nand subroutine arguments. It used to be easy to inadvertently lose a\nvariable's value this way, but now it's much harder. Take this code:\n\nmy $f = 'foo';\nsub T {\nwhile ($i++ < 3) { my $f = $f; $f .= \"bar\"; print $f, \"\\n\" }\n}\n\nT;\nprint \"Finally $f\\n\";\n\nIf you are experiencing variable suicide, that \"my $f\" in the subroutine\ndoesn't pick up a fresh copy of the $f whose value is 'foo'. The output\nshows that inside the subroutine the value of $f leaks through when it\nshouldn't, as in this output:\n\nfoobar\nfoobarbar\nfoobarbarbar\nFinally foo\n\nThe $f that has \"bar\" added to it three times should be a new $f \"my $f\"\nshould create a new lexical variable each time through the loop. The\nexpected output is:\n\nfoobar\nfoobar\nfoobar\nFinally foo\n\nHow can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?\nYou need to pass references to these objects. See \"Pass by Reference\" in\nperlsub for this particular question, and perlref for information on\nreferences.\n\nPassing Variables and Functions\nRegular variables and functions are quite easy to pass: just pass in\na reference to an existing or anonymous variable or function:\n\nfunc( \\$somescalar );\n\nfunc( \\@somearray  );\nfunc( [ 1 .. 10 ]   );\n\nfunc( \\%somehash   );\nfunc( { this => 10, that => 20 }   );\n\nfunc( \\&somefunc   );\nfunc( sub { $[0]  $[1] }   );\n\nPassing Filehandles\nAs of Perl 5.6, you can represent filehandles with scalar variables\nwhich you treat as any other scalar.\n\nopen my $fh, $filename or die \"Cannot open $filename! $!\";\nfunc( $fh );\n\nsub func {\nmy $passedfh = shift;\n\nmy $line = <$passedfh>;\n}\n\nBefore Perl 5.6, you had to use the *FH or \"\\*FH\" notations. These\nare \"typeglobs\"--see \"Typeglobs and Filehandles\" in perldata and\nespecially \"Pass by Reference\" in perlsub for more information.\n\nPassing Regexes\nHere's an example of how to pass in a string and a regular\nexpression for it to match against. You construct the pattern with\nthe \"qr//\" operator:\n\nsub compare {\nmy ($val1, $regex) = @;\nmy $retval = $val1 =~ /$regex/;\nreturn $retval;\n}\n$match = compare(\"old McDonald\", qr/d.*D/i);\n\nPassing Methods\nTo pass an object method into a subroutine, you can do this:\n\ncallalot(10, $someobj, \"methname\")\nsub callalot {\nmy ($count, $widget, $trick) = @;\nfor (my $i = 0; $i < $count; $i++) {\n$widget->$trick();\n}\n}\n\nOr, you can use a closure to bundle up the object, its method call,\nand arguments:\n\nmy $whatnot = sub { $someobj->obfuscate(@args) };\nfunc($whatnot);\nsub func {\nmy $code = shift;\n&$code();\n}\n\nYou could also investigate the can() method in the UNIVERSAL class\n(part of the standard perl distribution).\n\nHow do I create a static variable?\n(contributed by brian d foy)\n\nIn Perl 5.10, declare the variable with \"state\". The \"state\" declaration\ncreates the lexical variable that persists between calls to the\nsubroutine:\n\nsub counter { state $count = 1; $count++ }\n\nYou can fake a static variable by using a lexical variable which goes\nout of scope. In this example, you define the subroutine \"counter\", and\nit uses the lexical variable $count. Since you wrap this in a BEGIN\nblock, $count is defined at compile-time, but also goes out of scope at\nthe end of the BEGIN block. The BEGIN block also ensures that the\nsubroutine and the value it uses is defined at compile-time so the\nsubroutine is ready to use just like any other subroutine, and you can\nput this code in the same place as other subroutines in the program text\n(i.e. at the end of the code, typically). The subroutine \"counter\" still\nhas a reference to the data, and is the only way you can access the\nvalue (and each time you do, you increment the value). The data in chunk\nof memory defined by $count is private to \"counter\".\n\nBEGIN {\nmy $count = 1;\nsub counter { $count++ }\n}\n\nmy $start = counter();\n\n.... # code that calls counter();\n\nmy $end = counter();\n\nIn the previous example, you created a function-private variable because\nonly one function remembered its reference. You could define multiple\nfunctions while the variable is in scope, and each function can share\nthe \"private\" variable. It's not really \"static\" because you can access\nit outside the function while the lexical variable is in scope, and even\ncreate references to it. In this example, \"incrementcount\" and\n\"returncount\" share the variable. One function adds to the value and\nthe other simply returns the value. They can both access $count, and\nsince it has gone out of scope, there is no other way to access it.\n\nBEGIN {\nmy $count = 1;\nsub incrementcount { $count++ }\nsub returncount    { $count }\n}\n\nTo declare a file-private variable, you still use a lexical variable. A\nfile is also a scope, so a lexical variable defined in the file cannot\nbe seen from any other file.\n\nSee \"Persistent Private Variables\" in perlsub for more information. The\ndiscussion of closures in perlref may help you even though we did not\nuse anonymous subroutines in this answer. See \"Persistent Private\nVariables\" in perlsub for details.\n\nWhat's the difference between dynamic and lexical (static) scoping? Between local() and my()?\n\"local($x)\" saves away the old value of the global variable $x and\nassigns a new value for the duration of the subroutine *which is visible\nin other functions called from that subroutine*. This is done at\nrun-time, so is called dynamic scoping. local() always affects global\nvariables, also called package variables or dynamic variables.\n\n\"my($x)\" creates a new variable that is only visible in the current\nsubroutine. This is done at compile-time, so it is called lexical or\nstatic scoping. my() always affects private variables, also called\nlexical variables or (improperly) static(ly scoped) variables.\n\nFor instance:\n\nsub visible {\nprint \"var has value $var\\n\";\n}\n\nsub dynamic {\nlocal $var = 'local';    # new temporary value for the still-global\nvisible();              #   variable called $var\n}\n\nsub lexical {\nmy $var = 'private';    # new private variable, $var\nvisible();              # (invisible outside of sub scope)\n}\n\n$var = 'global';\n\nvisible();              # prints global\ndynamic();              # prints local\nlexical();              # prints global\n\nNotice how at no point does the value \"private\" get printed. That's\nbecause $var only has that value within the block of the lexical()\nfunction, and it is hidden from the called subroutine.\n\nIn summary, local() doesn't make what you think of as private, local\nvariables. It gives a global variable a temporary value. my() is what\nyou're looking for if you want private variables.\n\nSee \"Private Variables via my()\" in perlsub and \"Temporary Values via"
                    },
                    {
                        "name": "local",
                        "content": "How can I access a dynamic variable while a similarly named lexical is in scope?\nIf you know your package, you can just mention it explicitly, as in\n$SomePack::var. Note that the notation $::var is not the dynamic $var\nin the current package, but rather the one in the \"main\" package, as\nthough you had written $main::var.\n\nuse vars '$var';\nlocal $var = \"global\";\nmy    $var = \"lexical\";\n\nprint \"lexical is $var\\n\";\nprint \"global  is $main::var\\n\";\n\nAlternatively you can use the compiler directive our() to bring a\ndynamic variable into the current lexical scope.\n\nrequire 5.006; # our() did not exist before 5.6\nuse vars '$var';\n\nlocal $var = \"global\";\nmy $var    = \"lexical\";\n\nprint \"lexical is $var\\n\";\n\n{\nour $var;\nprint \"global  is $var\\n\";\n}\n\nWhat's the difference between deep and shallow binding?\nIn deep binding, lexical variables mentioned in anonymous subroutines\nare the same ones that were in scope when the subroutine was created. In\nshallow binding, they are whichever variables with the same names happen\nto be in scope when the subroutine is called. Perl always uses deep\nbinding of lexical variables (i.e., those created with my()). However,\ndynamic variables (aka global, local, or package variables) are\neffectively shallowly bound. Consider this just one more reason not to\nuse them. See the answer to \"What's a closure?\".\n\nWhy doesn't \"my($foo) = <$fh>;\" work right?\n\"my()\" and \"local()\" give list context to the right hand side of \"=\".\nThe <$fh> read operation, like so many of Perl's functions and\noperators, can tell which context it was called in and behaves\nappropriately. In general, the scalar() function can help. This function\ndoes nothing to the data itself (contrary to popular myth) but rather\ntells its argument to behave in whatever its scalar fashion is. If that\nfunction doesn't have a defined scalar behavior, this of course doesn't\nhelp you (such as with 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 do I create a switch or case statement?\nThere is a given/when statement in Perl, but it is experimental and\nlikely to change in future. See perlsyn for more details.\n\nThe general answer is to use a CPAN module such as Switch::Plain:\n\nuse Switch::Plain;\nsswitch($variableholdingastring) {\ncase 'first': { }\ncase 'second': { }\ndefault: { }\n}\n\nor for more complicated comparisons, \"if-elsif-else\":\n\nfor ($variabletotest) {\nif    (/pat1/)  { }     # do something\nelsif (/pat2/)  { }     # do something else\nelsif (/pat3/)  { }     # do something else\nelse            { }     # default\n}\n\nHere's a simple example of a switch based on pattern matching, lined up\nin a way to make it look more like a switch statement. We'll do a\nmultiway conditional based on the type of reference stored in\n$whatchamacallit:\n\nSWITCH: for (ref $whatchamacallit) {\n\n/^$/           && die \"not a reference\";\n\n/SCALAR/       && do {\nprintscalar($$ref);\nlast SWITCH;\n};\n\n/ARRAY/        && do {\nprintarray(@$ref);\nlast SWITCH;\n};\n\n/HASH/        && do {\nprinthash(%$ref);\nlast SWITCH;\n};\n\n/CODE/        && do {\nwarn \"can't print function ref\";\nlast SWITCH;\n};\n\n# DEFAULT\n\nwarn \"User defined type skipped\";\n\n}\n\nSee perlsyn for other examples in this style.\n\nSometimes you should change the positions of the constant and the\nvariable. For example, let's say you wanted to test which of many\nanswers you were given, but in a case-insensitive way that also allows\nabbreviations. You can use the following technique if the strings all\nstart with different characters or if you want to arrange the matches so\nthat one takes precedence over another, as \"SEND\" has precedence over\n\"STOP\" here:\n\nchomp($answer = <>);\nif    (\"SEND\"  =~ /^\\Q$answer/i) { print \"Action is send\\n\"  }\nelsif (\"STOP\"  =~ /^\\Q$answer/i) { print \"Action is stop\\n\"  }\nelsif (\"ABORT\" =~ /^\\Q$answer/i) { print \"Action is abort\\n\" }\nelsif (\"LIST\"  =~ /^\\Q$answer/i) { print \"Action is list\\n\"  }\nelsif (\"EDIT\"  =~ /^\\Q$answer/i) { print \"Action is edit\\n\"  }\n\nA totally different approach is to create a hash of function references.\n\nmy %commands = (\n\"happy\" => \\&joy,\n\"sad\",  => \\&sullen,\n\"done\"  => sub { die \"See ya!\" },\n\"mad\"   => \\&angry,\n);\n\nprint \"How are you? \";\nchomp($string = <STDIN>);\nif ($commands{$string}) {\n$commands{$string}->();\n} else {\nprint \"No such command: $string\\n\";\n}\n\nStarting from Perl 5.8, a source filter module, \"Switch\", can also be\nused to get switch and case. Its use is now discouraged, because it's\nnot fully compatible with the native switch of Perl 5.10, and because,\nas it's implemented as a source filter, it doesn't always work as\nintended when complex syntax is involved.\n\nHow can I catch accesses to undefined variables, functions, or methods?\nThe AUTOLOAD method, discussed in \"Autoloading\" in perlsub lets you\ncapture calls to undefined functions and methods.\n\nWhen it comes to undefined variables that would trigger a warning under\n\"use warnings\", you can promote the warning to an error.\n\nuse warnings FATAL => qw(uninitialized);\n\nWhy can't a method included in this same file be found?\nSome possible reasons: your inheritance is getting confused, you've\nmisspelled the method name, or the object is of the wrong type. Check\nout perlootut for details about any of the above cases. You may also use\n\"print ref($object)\" to find out the class $object was blessed into.\n\nAnother possible reason for problems is that you've used the indirect\nobject syntax (eg, \"find Guru \"Samy\"\") on a class name before Perl has\nseen that such a package exists. It's wisest to make sure your packages\nare all defined before you start using them, which will be taken care of\nif you use the \"use\" statement instead of \"require\". If not, make sure\nto use arrow notation (eg., \"Guru->find(\"Samy\")\") instead. Object\nnotation is explained in perlobj.\n\nMake sure to read about creating modules in perlmod and the perils of\nindirect objects in \"Method Invocation\" in perlobj.\n\nHow can I find out my current or calling package?\n(contributed by brian d foy)\n\nTo find the package you are currently in, use the special literal\n\"PACKAGE\", as documented in perldata. You can only use the special\nliterals as separate tokens, so you can't interpolate them into strings\nlike you can with variables:\n\nmy $currentpackage = PACKAGE;\nprint \"I am in package $currentpackage\\n\";\n\nIf you want to find the package calling your code, perhaps to give\nbetter diagnostics as Carp does, use the \"caller\" built-in:\n\nsub foo {\nmy @args = ...;\nmy( $package, $filename, $line ) = caller;\n\nprint \"I was called from package $package\\n\";\n);\n\nBy default, your program starts in package \"main\", so you will always be\nin some package.\n\nThis is different from finding out the package an object is blessed\ninto, which might not be the current package. For that, use \"blessed\"\nfrom Scalar::Util, part of the Standard Library since Perl 5.8:\n\nuse Scalar::Util qw(blessed);\nmy $objectpackage = blessed( $object );\n\nMost of the time, you shouldn't care what package an object is blessed\ninto, however, as long as it claims to inherit from that class:\n\nmy $isrightclass = eval { $object->isa( $package ) }; # true or false\n\nAnd, with Perl 5.10 and later, you don't have to check for an\ninheritance to see if the object can handle a role. For that, you can\nuse \"DOES\", which comes from \"UNIVERSAL\":\n\nmy $classdoesit = eval { $object->DOES( $role ) }; # true or false\n\nYou can safely replace \"isa\" with \"DOES\" (although the converse is not\ntrue).\n\nHow can I comment out a large block of Perl code?\n(contributed by brian d foy)\n\nThe quick-and-dirty way to comment out more than one line of Perl is to\nsurround those lines with Pod directives. You have to put these\ndirectives at the beginning of the line and somewhere where Perl expects\na new statement (so not in the middle of statements like the \"#\"\ncomments). You end the comment with \"=cut\", ending the Pod section:\n\n=pod\n\nmy $object = NotGonnaHappen->new();\n\nignoredsub();\n\n$wontbeassigned = 37;\n\n=cut\n\nThe quick-and-dirty method only works well when you don't plan to leave\nthe commented code in the source. If a Pod parser comes along, your\nmultiline comment is going to show up in the Pod translation. A better\nway hides it from Pod parsers as well.\n\nThe \"=begin\" directive can mark a section for a particular purpose. If\nthe Pod parser doesn't want to handle it, it just ignores it. Label the\ncomments with \"comment\". End the comment using \"=end\" with the same\nlabel. You still need the \"=cut\" to go back to Perl code from the Pod\ncomment:\n\n=begin comment\n\nmy $object = NotGonnaHappen->new();\n\nignoredsub();\n\n$wontbeassigned = 37;\n\n=end comment\n\n=cut\n\nFor more information on Pod, check out perlpod and perlpodspec.\n\nHow do I clear a package?\nUse this code, provided by Mark-Jason Dominus:\n\nsub scrubpackage {\nno strict 'refs';\nmy $pack = shift;\ndie \"Shouldn't delete main package\"\nif $pack eq \"\" || $pack eq \"main\";\nmy $stash = *{$pack . '::'}{HASH};\nmy $name;\nforeach $name (keys %$stash) {\nmy $fullname = $pack . '::' . $name;\n# Get rid of everything with that name.\nundef $$fullname;\nundef @$fullname;\nundef %$fullname;\nundef &$fullname;\nundef *$fullname;\n}\n}\n\nOr, if you're using a recent release of Perl, you can just use the\nSymbol::deletepackage() function instead.\n\nWhat does \"bad interpreter\" mean?\n(contributed by brian d foy)\n\nThe \"bad interpreter\" message comes from the shell, not perl. The actual\nmessage may vary depending on your platform, shell, and locale settings.\n\nIf you see \"bad interpreter - no such file or directory\", the first line\nin your perl script (the \"shebang\" line) does not contain the right path\nto perl (or any other program capable of running scripts). Sometimes\nthis happens when you move the script from one machine to another and\neach machine has a different path to perl--/usr/bin/perl versus\n/usr/local/bin/perl for instance. It may also indicate that the source\nmachine has CRLF line terminators and the destination machine has LF\nonly: the shell tries to find /usr/bin/perl<CR>, but can't.\n\nIf you see \"bad interpreter: Permission denied\", you need to make your\nscript executable.\n\nIn either case, you should still be able to run the scripts with perl\nexplicitly:\n\n% perl script.pl\n\nIf you get a message like \"perl: command not found\", perl is not in your\nPATH, which might also mean that the location of perl is not where you\nexpect it so you need to adjust your shebang line.\n\nDo I need to recompile XS modules when there is a change in the C library?\n(contributed by Alex Beamish)\n\nIf the new version of the C library is ABI-compatible (that's\nApplication Binary Interface compatible) with the version you're\nupgrading from, and if the shared library version didn't change, no\nre-compilation should be necessary.\n"
                    }
                ]
            },
            "Found in /usr/share/perl/5.34/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 come exec() doesn't return?\n(contributed by brian d foy)\n\nThe \"exec\" function's job is to turn your process into another command\nand never to return. If that's not what you want to do, don't use\n\"exec\". :)\n\nIf you want to run an external command and still keep your Perl process\ngoing, look at a piped \"open\", \"fork\", or \"system\".\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 print something out in color?\nIn general, you don't, because you don't know whether the recipient has\na color-aware display device. If you know that they have an ANSI\nterminal that understands color, you can use the Term::ANSIColor module\nfrom CPAN:\n\nuse Term::ANSIColor;\nprint color(\"red\"), \"Stop!\\n\", color(\"reset\");\nprint color(\"green\"), \"Go!\\n\", color(\"reset\");\n\nOr like this:\n\nuse Term::ANSIColor qw(:constants);\nprint RED, \"Stop!\\n\", RESET;\nprint GREEN, \"Go!\\n\", RESET;\n\nHow do I 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 check whether input is ready on the keyboard?\nThe easiest way to do this is to read a key in nonblocking mode with the\nTerm::ReadKey module from CPAN, passing it an argument of -1 to indicate\nnot to block:\n\nuse Term::ReadKey;\n\nReadMode('cbreak');\n\nif (defined (my $char = ReadKey(-1)) ) {\n# input was waiting and it was $char\n} else {\n# no input was waiting\n}\n\nReadMode('normal');                  # restore normal tty settings\n\nHow do I clear the screen?\n(contributed by brian d foy)\n\nTo clear the screen, you just have to print the special sequence that\ntells the terminal to clear the screen. Once you have that sequence,\noutput it when you want to clear the screen.\n\nYou can use the Term::ANSIScreen module to get the special sequence.\nImport the \"cls\" function (or the \":screen\" tag):\n\nuse Term::ANSIScreen qw(cls);\nmy $clearscreen = cls();\n\nprint $clearscreen;\n\nThe Term::Cap module can also get the special sequence if you want to\ndeal with the low-level details of terminal control. The \"Tputs\" method\nreturns the string for the given capability:\n\nuse Term::Cap;\n\nmy $terminal = Term::Cap->Tgetent( { OSPEED => 9600 } );\nmy $clearscreen = $terminal->Tputs('cl');\n\nprint $clearscreen;\n\nOn Windows, you can use the Win32::Console module. After creating an\nobject for the output filehandle you want to affect, call the \"Cls\"\nmethod:\n\nWin32::Console;\n\nmy $OUT = Win32::Console->new(STDOUTPUTHANDLE);\nmy $clearstring = $OUT->Cls;\n\nprint $clearscreen;\n\nIf you have a command-line program that does the job, you can call it in\nbackticks to capture whatever it outputs so you can use it later:\n\nmy $clearstring = `clear`;\n\nprint $clearstring;\n\nHow do I get the screen size?\nIf you have Term::ReadKey module installed from CPAN, you can use it to\nfetch the width and height in characters and in pixels:\n\nuse Term::ReadKey;\nmy ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();\n\nThis is more portable than the raw \"ioctl\", but not as illustrative:\n\nrequire './sys/ioctl.ph';\ndie \"no TIOCGWINSZ \" unless defined &TIOCGWINSZ;\nopen(my $ttyfh, \"+</dev/tty\")                     or die \"No tty: $!\";\nunless (ioctl($ttyfh, &TIOCGWINSZ, $winsize='')) {\ndie sprintf \"$0: ioctl TIOCGWINSZ (%08x: $!)\\n\", &TIOCGWINSZ;\n}\nmy ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);\nprint \"(row,col) = ($row,$col)\";\nprint \"  (xpixel,ypixel) = ($xpixel,$ypixel)\" if $xpixel || $ypixel;\nprint \"\\n\";\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 read and write the serial port?\nThis depends on which operating system your program is running on. In\nthe case of Unix, the serial ports will be accessible through files in\n\"/dev\"; on other systems, device names will doubtless differ. Several\nproblem areas common to all device interaction are the following:\n\nlockfiles\nYour system may use lockfiles to control multiple access. Make sure\nyou follow the correct protocol. Unpredictable behavior can result\nfrom multiple processes reading from one device.\n\nopen mode\nIf you expect to use both read and write operations on the device,\nyou'll have to open it for update (see \"open\" in perlfunc for\ndetails). You may wish to open it without running the risk of\nblocking by using \"sysopen()\" and \"ORDWR|ONDELAY|ONOCTTY\" from\nthe Fcntl module (part of the standard perl distribution). See\n\"sysopen\" in perlfunc for more on this approach.\n\nend of line\nSome devices will be expecting a \"\\r\" at the end of each line rather\nthan a \"\\n\". In some ports of perl, \"\\r\" and \"\\n\" are different from\ntheir usual (Unix) ASCII values of \"\\015\" and \"\\012\". You may have\nto give the numeric values you want directly, using octal (\"\\015\"),\nhex (\"0x0D\"), or as a control-character specification (\"\\cM\").\n\nprint DEV \"atv1\\012\";    # wrong, for some devices\nprint DEV \"atv1\\015\";    # right, for some devices\n\nEven though with normal text files a \"\\n\" will do the trick, there\nis still no unified scheme for terminating a line that is portable\nbetween Unix, DOS/Win, and Macintosh, except to terminate *ALL* line\nends with \"\\015\\012\", and strip what you don't need from the output.\nThis applies especially to socket I/O and autoflushing, discussed\nnext.\n\nflushing output\nIf you expect characters to get to your device when you \"print()\"\nthem, you'll want to autoflush that filehandle. You can use\n\"select()\" and the $| variable to control autoflushing (see \"$|\" in\nperlvar and \"select\" in perlfunc, or perlfaq5, \"How do I\nflush/unbuffer an output filehandle? Why must I do this?\"):\n\nmy $oldhandle = select($devfh);\n$| = 1;\nselect($oldhandle);\n\nYou'll also see code that does this without a temporary variable, as\nin\n\nselect((select($debhandle), $| = 1)[0]);\n\nOr if you don't mind pulling in a few thousand lines of code just\nbecause you're afraid of a little $| variable:\n\nuse IO::Handle;\n$devfh->autoflush(1);\n\nAs mentioned in the previous item, this still doesn't work when\nusing socket I/O between Unix and Macintosh. You'll need to hard\ncode your line terminators, in that case.\n\nnon-blocking input\nIf you are doing a blocking \"read()\" or \"sysread()\", you'll have to\narrange for an alarm handler to provide a timeout (see \"alarm\" in\nperlfunc). If you have a non-blocking open, you'll likely have a\nnon-blocking read, which means you may have to use a 4-arg\n\"select()\" to determine whether I/O is ready on that device (see\n\"select\" in perlfunc.\n\nWhile trying to read from his caller-id box, the notorious Jamie\nZawinski \"<jwz@netscape.com>\", after much gnashing of teeth and fighting\nwith \"sysread\", \"sysopen\", POSIX's \"tcgetattr\" business, and various\nother functions that go bump in the night, finally came up with this:\n\nsub openmodem {\nuse IPC::Open2;\nmy $stty = `/bin/stty -g`;\nopen2( \\*MODEMIN, \\*MODEMOUT, \"cu -l$modemdevice -s2400 2>&1\");\n# starting cu hoses /dev/tty's stty settings, even when it has\n# been opened on a pipe...\nsystem(\"/bin/stty $stty\");\n$ = <MODEMIN>;\nchomp;\nif ( !m/^Connected/ ) {\nprint STDERR \"$0: cu printed `$' instead of `Connected'\\n\";\n}\n}\n\nHow do I decode encrypted password files?\nYou spend lots and lots of money on dedicated hardware, but this is\nbound to get you talked about.\n\nSeriously, you can't if they are Unix password files--the Unix password\nsystem employs one-way encryption. It's more like hashing than\nencryption. The best you can do is check whether something else hashes\nto the same string. You can't turn a hash back into the original string.\nPrograms like Crack can forcibly (and intelligently) try to guess\npasswords, but don't (can't) guarantee quick success.\n\nIf you're worried about users selecting bad passwords, you should\nproactively check when they try to change their password (by modifying",
                "subsections": [
                    {
                        "name": "passwd",
                        "content": "How do I start a process in the background?\n(contributed by brian d foy)\n\nThere's not a single way to run code in the background so you don't have\nto wait for it to finish before your program moves on to other tasks.\nProcess management depends on your particular operating system, and many\nof the techniques are covered in perlipc.\n\nSeveral CPAN modules may be able to help, including IPC::Open2 or\nIPC::Open3, IPC::Run, Parallel::Jobs, Parallel::ForkManager, POE,\nProc::Background, and Win32::Process. There are many other modules you\nmight use, so check those namespaces for other options too.\n\nIf you are on a Unix-like system, you might be able to get away with a\nsystem call where you put an \"&\" on the end of the command:\n\nsystem(\"cmd &\")\n\nYou can also try using \"fork\", as described in perlfunc (although this\nis the same thing that many of the modules will do for you).\n\nSTDIN, STDOUT, and STDERR are shared\nBoth the main process and the backgrounded one (the \"child\" process)\nshare the same STDIN, STDOUT and STDERR filehandles. If both try to\naccess them at once, strange things can happen. You may want to\nclose or reopen these for the child. You can get around this with\n\"open\"ing a pipe (see \"open\" in perlfunc) but on some systems this\nmeans that the child process cannot outlive the parent.\n\nSignals\nYou'll have to catch the SIGCHLD signal, and possibly SIGPIPE too.\nSIGCHLD is sent when the backgrounded process finishes. SIGPIPE is\nsent when you write to a filehandle whose child process has closed\n(an untrapped SIGPIPE can cause your program to silently die). This\nis not an issue with \"system(\"cmd&\")\".\n\nZombies\nYou have to be prepared to \"reap\" the child process when it\nfinishes.\n\n$SIG{CHLD} = sub { wait };\n\n$SIG{CHLD} = 'IGNORE';\n\nYou can also use a double fork. You immediately \"wait()\" for your\nfirst child, and the init daemon will \"wait()\" for your grandchild\nonce it exits.\n\nunless ($pid = fork) {\nunless (fork) {\nexec \"what you really wanna do\";\ndie \"exec failed!\";\n}\nexit 0;\n}\nwaitpid($pid, 0);\n\nSee \"Signals\" in perlipc for other examples of code to do this.\nZombies are not an issue with \"system(\"prog &\")\".\n\nHow do I trap control characters/signals?\nYou don't actually \"trap\" a control character. Instead, that character\ngenerates a signal which is sent to your terminal's currently\nforegrounded process group, which you then trap in your process. Signals\nare documented in \"Signals\" in perlipc and the section on \"Signals\" in\nthe Camel.\n\nYou can set the values of the %SIG hash to be the functions you want to\nhandle the signal. After perl catches the signal, it looks in %SIG for a\nkey with the same name as the signal, then calls the subroutine value\nfor that key.\n\n# as an anonymous subroutine\n\n$SIG{INT} = sub { syswrite(STDERR, \"ouch\\n\", 5 ) };\n\n# or a reference to a function\n\n$SIG{INT} = \\&ouch;\n\n# or the name of the function as a string\n\n$SIG{INT} = \"ouch\";\n\nPerl versions before 5.8 had in its C source code signal handlers which\nwould catch the signal and possibly run a Perl function that you had set\nin %SIG. This violated the rules of signal handling at that level\ncausing perl to dump core. Since version 5.8.0, perl looks at %SIG after\nthe signal has been caught, rather than while it is being caught.\nPrevious versions of this answer were incorrect.\n\nHow do I modify the shadow password file on a Unix system?\nIf perl was installed correctly and your shadow library was written\nproperly, the \"getpw*()\" functions described in perlfunc should in\ntheory provide (read-only) access to entries in the shadow password\nfile. To change the file, make a new shadow password file (the format\nvaries from system to system--see passwd(1) for specifics) and use"
                    },
                    {
                        "name": "pwd_mkdb",
                        "content": "How do I set the time and date?\nAssuming you're running under sufficient permissions, you should be able\nto set the system-wide date and time by running the date(1) program.\n(There is no way to set the time and date on a per-process basis.) This\nmechanism will work for Unix, MS-DOS, Windows, and NT; the VMS\nequivalent is \"set time\".\n\nHowever, if all you want to do is change your time zone, you can\nprobably get away with setting an environment variable:\n\n$ENV{TZ} = \"MST7MDT\";           # Unixish\n$ENV{'SYS$TIMEZONEDIFFERENTIAL'}=\"-5\" # vms\nsystem('trn', 'comp.lang.perl.misc');\n\nHow 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 measure time under a second?\n(contributed by brian d foy)\n\nThe Time::HiRes module (part of the standard distribution as of Perl\n5.8) measures time with the \"gettimeofday()\" system call, which returns\nthe time in microseconds since the epoch. If you can't install\nTime::HiRes for older Perls and you are on a Unixish system, you may be\nable to call gettimeofday(2) directly. See \"syscall\" in perlfunc.\n\nHow can I do an atexit() or setjmp()/longjmp()? (Exception handling)\nYou can use the \"END\" block to simulate \"atexit()\". Each package's \"END\"\nblock is called when the program or thread ends. See the perlmod manpage\nfor more details about \"END\" blocks.\n\nFor example, you can use this to make sure your filter program managed\nto finish its output without filling up the disk:\n\nEND {\nclose(STDOUT) || die \"stdout close failed: $!\";\n}\n\nThe \"END\" block isn't called when untrapped signals kill the program,\nthough, so if you use \"END\" blocks you should also use\n\nuse sigtrap qw(die normal-signals);\n\nPerl's exception-handling mechanism is its \"eval()\" operator. You can\nuse \"eval()\" as \"setjmp\" and \"die()\" as \"longjmp\". For details of this,\nsee the section on signals, especially the time-out handler for a\nblocking \"flock()\" in \"Signals\" in perlipc or the section on \"Signals\"\nin *Programming Perl*.\n\nIf exception handling is all you're interested in, use one of the many\nCPAN modules that handle exceptions, such as Try::Tiny.\n\nIf you want the \"atexit()\" syntax (and an \"rmexit()\" as well), try the\n\"AtExit\" module available from CPAN.\n\nWhy doesn't my sockets program work under System V (Solaris)? What does the error message \"Protocol not supported\" mean?\nSome Sys-V based systems, notably Solaris 2.X, redefined some of the\nstandard socket constants. Since these were constant across all\narchitectures, they were often hardwired into perl code. The proper way\nto deal with this is to \"use Socket\" to get the correct values.\n\nNote that even though SunOS and Solaris are binary compatible, these\nvalues are different. Go figure.\n\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\n\"SYSgetitimer()\", which you can use as arguments to your functions. It\ndoesn't work perfectly, but it usually gets most of the job done. Simple\nfiles like errno.h, syscall.h, and socket.h were fine, but the hard ones\nlike ioctl.h nearly always need to be hand-edited. Here's how to install\nthe *.ph files:\n\n1. Become the super-user\n2. cd /usr/include\n3. h2ph *.h */*.h\n\nIf your system supports dynamic loading, for reasons of portability and\nsanity you probably ought to use h2xs (also part of the standard perl\ndistribution). This tool converts C header files to Perl extensions. See\nperlxstut for how to get started with h2xs.\n\nIf your system doesn't support dynamic loading, you still probably ought\nto use h2xs. See perlxstut and ExtUtils::MakeMaker for more information\n(in brief, just use make perl instead of a plain make to rebuild perl\nwith a new static extension).\n\nWhy do setuid perl scripts complain about kernel problems?\nSome operating systems have bugs in the kernel that make setuid scripts\ninherently insecure. Perl gives you a number of options (described in\nperlsec) to work around such systems.\n\nHow can I 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\n\"exec()\" to do 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 (``).\n\"system()\" runs a command and returns exit status information (as a 16\nbit value: the low 7 bits are the signal the process died from, if any,\nand the high 8 bits are the actual exit value). Backticks (``) run a\ncommand and return 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\nthem. Backticks and \"open()\" read only the STDOUT of your command.\n\nYou can also use the \"open3()\" function from IPC::Open3. Benjamin\nGoldberg provides 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\ngoing at the time of the \"open()\". The backticks then make STDOUT go to\na string, 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\nmetacharacters, perl \"fork()\"s, then \"exec()\"s a shell to decode the\nmetacharacters and eventually run the desired program. If the program\ncouldn't be run, it's the shell that gets the message, not Perl. All\nyour Perl program can find out is whether the shell itself could be\nsuccessfully started. You can still capture the shell's STDERR and check\nit for error messages. See \"How can I capture STDERR from an external\ncommand?\" elsewhere in this 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\nWhat's wrong with using backticks in a void context?\nStrictly speaking, nothing. Stylistically speaking, it's not a good way\nto write maintainable code. Perl has several operators for running\nexternal commands. Backticks are one; they collect the output from the\ncommand for use in your program. The \"system\" function is another; it\ndoesn't do this.\n\nWriting backticks in your program sends a clear message to the readers\nof your code that you wanted to collect the output of the command. Why\nsend a clear message that isn't true?\n\nConsider this line:\n\n`cat /etc/termcap`;\n\nYou forgot to check $? to see whether the program even ran correctly.\nEven if you wrote\n\nprint `cat /etc/termcap`;\n\nthis code could and probably should be written as\n\nsystem(\"cat /etc/termcap\") == 0\nor die \"cat program failed!\";\n\nwhich will echo the cat command's output as it is generated, instead of\nwaiting until the program has completed to print it out. It also checks\nthe return value.\n\n\"system\" also provides direct control over whether shell wildcard\nprocessing may take place, whereas backticks do not.\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\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 timeout a slow event?\nUse the \"alarm()\" function, probably in conjunction with a signal\nhandler, as documented in \"Signals\" in perlipc and the section on\n\"Signals\" in the Camel. You may instead use the more flexible\nSys::AlarmCall module available from CPAN.\n\nThe \"alarm()\" function is not implemented on all versions of Windows.\nCheck the documentation for your specific version of Perl.\n\nHow do I set CPU limits?\n(contributed by Xho)\n\nUse the BSD::Resource module from CPAN. As an example:\n\nuse BSD::Resource;\nsetrlimit(RLIMITCPU,10,20) or die $!;\n\nThis sets the soft and hard limits to 10 and 20 seconds, respectively.\nAfter 10 seconds of time spent running on the CPU (not \"wall\" time), the\nprocess will be sent a signal (XCPU on some systems) which, if not\ntrapped, will cause the process to terminate. If that signal is trapped,\nthen after 10 more seconds (20 seconds in total) the process will be\nkilled with a non-trappable signal.\n\nSee the BSD::Resource and your systems documentation for the gory\ndetails.\n\nHow do I avoid zombies on a Unix system?\nUse the reaper code from \"Signals\" in perlipc to call \"wait()\" when a\nSIGCHLD is received, or else use the double-fork technique described in\n\"How do I start a process in the background?\" in perlfaq8.\n\nHow do I use an SQL database?\nThe DBI module provides an abstract interface to most database servers\nand types, including Oracle, DB2, Sybase, mysql, Postgresql, ODBC, and\nflat files. The DBI module accesses each database type through a\ndatabase driver, or DBD. You can see a complete list of available\ndrivers on CPAN: <http://www.cpan.org/modules/by-module/DBD/> . You can\nread more about DBI on <http://dbi.perl.org/> .\n\nOther modules provide more specific access: Win32::ODBC, Alzabo,\n\"iodbc\", and others found on CPAN Search: <https://metacpan.org/> .\n\nHow do I make a system() exit on control-C?\nYou can't. You need to imitate the \"system()\" call (see perlipc for\nsample code) and then have a signal handler for the INT signal that\npasses the signal on to the subprocess. Or you can check for it:\n\n$rc = system($cmd);\nif ($rc & 127) { die \"signal death\" }\n\nHow do I open a file without blocking?\nIf you're lucky enough to be using a system that supports non-blocking\nreads (most Unixish systems do), you need only to use the \"ONDELAY\" or\n\"ONONBLOCK\" flag from the \"Fcntl\" module in conjunction with\n\"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\nshebang line is not the path to perl, so the shell runs the script, and\nI get the 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\nHow do I keep my own module/library directory?\nWhen you build modules, tell Perl where to install the modules.\n\nIf you want to install modules for your own use, the easiest way might\nbe local::lib, which you can download from CPAN. It sets various\ninstallation settings for you, and uses those same settings within your\nprograms.\n\nIf you want more flexibility, you need to configure your CPAN client for\nyour particular situation.\n\nFor \"Makefile.PL\"-based distributions, use the INSTALLBASE option when\ngenerating Makefiles:\n\nperl Makefile.PL INSTALLBASE=/mydir/perl\n\nYou can set this in your \"CPAN.pm\" configuration so modules\nautomatically install in your private library directory when you use the\nCPAN.pm shell:\n\n% cpan\ncpan> o conf makeplarg INSTALLBASE=/mydir/perl\ncpan> o conf commit\n\nFor \"Build.PL\"-based distributions, use the --installbase option:\n\nperl Build.PL --installbase /mydir/perl\n\nYou can configure \"CPAN.pm\" to automatically use this option too:\n\n% cpan\ncpan> o conf mbuildarg \"--installbase /mydir/perl\"\ncpan> o conf commit\n\nINSTALLBASE tells these tools to put your modules into\n/mydir/perl/lib/perl5. See \"How do I add a directory to my include path\n(@INC) at runtime?\" for details on how to run your newly installed\nmodules.\n\nThere is one caveat with INSTALLBASE, though, since it acts differently\nfrom the PREFIX and LIB settings that older versions of\nExtUtils::MakeMaker advocated. INSTALLBASE does not support installing\nmodules for multiple versions of Perl or different architectures under\nthe same directory. You should consider whether you really want that\nand, if you do, use the older PREFIX and LIB settings. See the\nExtUtils::Makemaker documentation for more details.\n\nHow do I add the directory my program lives in to the module/library search path?\n(contributed by brian d foy)\n\nIf you know the directory already, you can add it to @INC as you would\nfor any other directory. You might \"use lib\" if you know the directory\nat compile time:\n\nuse lib $directory;\n\nThe trick in this task is to find the directory. Before your script does\nanything else (such as a \"chdir\"), you can get the current working\ndirectory with the \"Cwd\" module, which comes with Perl:\n\nBEGIN {\nuse Cwd;\nour $directory = cwd;\n}\n\nuse lib $directory;\n\nYou can do a similar thing with the value of $0, which holds the script\nname. That might hold a relative path, but \"rel2abs\" can turn it into an\nabsolute path. Once you have the\n\nBEGIN {\nuse File::Spec::Functions qw(rel2abs);\nuse File::Basename qw(dirname);\n\nmy $path   = rel2abs( $0 );\nour $directory = dirname( $path );\n}\n\nuse lib $directory;\n\nThe FindBin module, which comes with Perl, might work. It finds the\ndirectory of the currently running script and puts it in $Bin, which you\ncan then use to construct the right library path:\n\nuse FindBin qw($Bin);\n\nYou can also use local::lib to do much of the same thing. Install\nmodules using local::lib's settings then use the module in your program:\n\nuse local::lib; # sets up a local lib at ~/perl5\n\nSee the local::lib documentation for more details.\n\nHow do I add a directory to my include path (@INC) at runtime?\nHere are the suggested ways of modifying your include path, including\nenvironment variables, run-time switches, and in-code statements:\n\nthe \"PERLLIB\" environment variable\n$ export PERLLIB=/path/to/my/dir\n$ perl program.pl\n\nthe \"PERL5LIB\" environment variable\n$ export PERL5LIB=/path/to/my/dir\n$ perl program.pl\n\nthe \"perl -Idir\" command line flag\n$ perl -I/path/to/my/dir program.pl\n\nthe \"lib\" pragma:\nuse lib \"$ENV{HOME}/myownperllib\";\n\nthe local::lib module:\nuse local::lib;\n\nuse local::lib \"~/myownperllib\";\n\nWhere are modules installed?\nModules are installed on a case-by-case basis (as provided by the\nmethods described in the previous section), and in the operating system.\nAll of these paths are stored in @INC, which you can display with the\none-liner\n\nperl -e 'print join(\"\\n\",@INC,\"\")'\n\nThe same information is displayed at the end of the output from the\ncommand\n\nperl -V\n\nTo find out where a module's source code is located, use\n\nperldoc -l Encode\n\nto display the path to the module. In some cases (for example, the\n\"AutoLoader\" module), this command will show the path to a separate\n\"pod\" file; the module itself should be in the same directory, with a\n'pm' file extension.\n\nWhat is socket.ph and where do I get it?\nIt's a Perl 4 style file defining values for system networking\nconstants. Sometimes it is built using h2ph when Perl is installed, but\nother times it is not. Modern programs should use \"use Socket;\" instead.\n"
                    }
                ]
            },
            "Found in /usr/share/perl/5.34/pod/perlfaq9.pod": {
                "content": "Should I use a web framework?\nYes. If you are building a web site with any level of interactivity\n(forms / users / databases), you will want to use a framework to make\nhandling requests and responses easier.\n\nIf there is no interactivity then you may still want to look at using\nsomething like Template Toolkit <https://metacpan.org/module/Template>\nor Plack::Middleware::TemplateToolkit so maintenance of your HTML files\n(and other assets) is easier.\n\nWhich web framework should I use?\nThere is no simple answer to this question. Perl frameworks can run\neverything from basic file servers and small scale intranets to massive\nmultinational multilingual websites that are the core to international\nbusinesses.\n\nBelow is a list of a few frameworks with comments which might help you\nin making a decision, depending on your specific requirements. Start by\nreading the docs, then ask questions on the relevant mailing list or IRC\nchannel.\n\nCatalyst\nStrongly object-oriented and fully-featured with a long development\nhistory and a large community and addon ecosystem. It is excellent\nfor large and complex applications, where you have full control over\nthe server.\n\nDancer2\nFree of legacy weight, providing a lightweight and easy to learn\nAPI. Has a growing addon ecosystem. It is best used for smaller\nprojects and very easy to learn for beginners.\n\nMojolicious\nSelf-contained and powerful for both small and larger projects, with\na focus on HTML5 and real-time web technologies such as WebSockets.\n\nWeb::Simple\nStrongly object-oriented and minimal, built for speed and intended\nas a toolkit for building micro web apps, custom frameworks or for\ntieing together existing Plack-compatible web applications with one\ncentral dispatcher.\n\nAll of these interact with or use Plack which is worth understanding the\nbasics of when building a website in Perl (there is a lot of useful\nPlack::Middleware\n<https://metacpan.org/search?q=plack%3A%3Amiddleware>).\n\nWhat is Plack and PSGI?\nPSGI is the Perl Web Server Gateway Interface Specification, it is a\nstandard that many Perl web frameworks use, you should not need to\nunderstand it to build a web site, the part you might want to use is\nPlack.\n\nPlack is a set of tools for using the PSGI stack. It contains middleware\n<https://metacpan.org/search?q=plack%3A%3Amiddleware> components, a\nreference server and utilities for Web application frameworks. Plack is\nlike Ruby's Rack or Python's Paste for WSGI.\n\nYou could build a web site using Plack and your own code, but for\nanything other than a very basic web site, using a web framework (that\nuses <https://plackperl.org>) is a better option.\n\nHow do I remove HTML from a string?\nUse HTML::Strip, or HTML::FormatText which not only removes HTML but\nalso attempts to do a little simple formatting of the resulting plain\ntext.\n\nHow do I extract URLs?\nHTML::SimpleLinkExtor will extract URLs from HTML, it handles anchors,\nimages, objects, frames, and many other tags that can contain a URL. If\nyou need anything more complex, you can create your own subclass of\nHTML::LinkExtor or HTML::Parser. You might even use\nHTML::SimpleLinkExtor as an example for something specifically suited to\nyour needs.\n\nYou can use URI::Find or URL::Search to extract URLs from an arbitrary\ntext document.\n\nHow do I fetch an HTML file?\n(contributed by brian d foy)\n\nThe core HTTP::Tiny module can fetch web resources and give their\ncontent back to you as a string:\n\nuse HTTP::Tiny;\n\nmy $ua = HTTP::Tiny->new;\nmy $html = $ua->get( \"http://www.example.com/index.html\" )->{content};\n\nIt can also store the resource directly in a file:\n\n$ua->mirror( \"http://www.example.com/index.html\", \"foo.html\" );\n\nIf you need to do something more complicated, the HTTP::Tiny object can\nbe customized by setting attributes, or you can use LWP::UserAgent from\nthe libwww-perl distribution or Mojo::UserAgent from the Mojolicious\ndistribution to make common tasks easier. If you want to simulate an\ninteractive web browser, you can use the WWW::Mechanize module.\n\nHow do I automate an HTML form submission?\nIf you are doing something complex, such as moving through many pages\nand forms or a web site, you can use WWW::Mechanize. See its\ndocumentation for all the details.\n\nIf you're submitting values using the GET method, create a URL and\nencode the form using the \"wwwformurlencode\" method from HTTP::Tiny:\n\nuse HTTP::Tiny;\n\nmy $ua = HTTP::Tiny->new;\n\nmy $query = $ua->wwwformurlencode([ q => 'DBFile', lucky => 1 ]);\nmy $url = \"https://metacpan.org/search?$query\";\nmy $content = $ua->get($url)->{content};\n\nIf you're using the POST method, the \"postform\" method will encode the\ncontent appropriately.\n\nuse HTTP::Tiny;\n\nmy $ua = HTTP::Tiny->new;\n\nmy $url = 'https://metacpan.org/search';\nmy $form = [ q => 'DBFile', lucky => 1 ];\nmy $content = $ua->postform($url, $form)->{content};\n\nHow do I decode or create those %-encodings on the web?\nMost of the time you should not need to do this as your web framework,\nor if you are making a request, the LWP or other module would handle it\nfor you.\n\nTo encode a string yourself, use the URI::Escape module. The\n\"uriescape\" function returns the escaped string:\n\nmy $original = \"Colon : Hash # Percent %\";\n\nmy $escaped = uriescape( $original );\n\nprint \"$escaped\\n\"; # 'Colon%20%3A%20Hash%20%23%20Percent%20%25'\n\nTo decode the string, use the \"uriunescape\" function:\n\nmy $unescaped = uriunescape( $escaped );\n\nprint $unescaped; # back to original\n\nRemember not to encode a full URI, you need to escape each component\nseparately and then join them together.\n\nHow do I redirect to another page?\nMost Perl Web Frameworks will have a mechanism for doing this, using the\nCatalyst framework it would be:\n\n$c->res->redirect($url);\n$c->detach();\n\nIf you are using Plack (which most frameworks do), then\nPlack::Middleware::Rewrite is worth looking at if you are migrating from\nApache or have URL's you want to always redirect.\n\nHow do I put a password on my web pages?\nSee if the web framework you are using has an authentication system and\nif that fits your needs.\n\nAlternativly look at Plack::Middleware::Auth::Basic, or one of the other\nPlack authentication <https://metacpan.org/search?q=plack+auth> options.\n\nHow do I make sure users can't enter values into a form that causes my CGI script to do bad things?\n(contributed by brian d foy)\n\nYou can't prevent people from sending your script bad data. Even if you\nadd some client-side checks, people may disable them or bypass them\ncompletely. For instance, someone might use a module such as LWP to\nsubmit to your web site. If you want to prevent data that try to use SQL\ninjection or other sorts of attacks (and you should want to), you have\nto not trust any data that enter your program.\n\nThe perlsec documentation has general advice about data security. If you\nare using the DBI module, use placeholder to fill in data. If you are\nrunning external programs with \"system\" or \"exec\", use the list forms.\nThere are many other precautions that you should take, too many to list\nhere, and most of them fall under the category of not using any data\nthat you don't intend to use. Trust no one.\n\nHow do I parse a mail header?\nUse the Email::MIME module. It's well-tested and supports all the\ncraziness that you'll see in the real world (comment-folding whitespace,\nencodings, comments, etc.).\n\nuse Email::MIME;\n\nmy $message = Email::MIME->new($rfc2822);\nmy $subject = $message->header('Subject');\nmy $from    = $message->header('From');\n\nIf you've already got some other kind of email object, consider passing\nit to Email::Abstract and then using its cast method to get an\nEmail::MIME object:\n\nmy $abstract = Email::Abstract->new($mailmessageobject);\nmy $emailmimeobject = $abstract->cast('Email::MIME');\n\nHow do I check a valid mail address?\n(partly contributed by Aaron Sherman)\n\nThis isn't as simple a question as it sounds. There are two parts:\n\na) How do I verify that an email address is correctly formatted?\n\nb) How do I verify that an email address targets a valid recipient?\n\nWithout sending mail to the address and seeing whether there's a human\non the other end to answer you, you cannot fully answer part *b*, but\nthe Email::Valid module will do both part *a* and part *b* as far as you\ncan in real-time.\n\nOur best advice for verifying a person's mail address is to have them\nenter their address twice, just as you normally do to change a password.\nThis usually weeds out typos. If both versions match, send mail to that\naddress with a personal message. If you get the message back and they've\nfollowed your directions, you can be reasonably assured that it's real.\n\nA related strategy that's less open to forgery is to give them a PIN\n(personal ID number). Record the address and PIN (best that it be a\nrandom one) for later processing. In the mail you send, include a link\nto your site with the PIN included. If the mail bounces, you know it's\nnot valid. If they don't click on the link, either they forged the\naddress or (assuming they got the message) following through wasn't\nimportant so you don't need to worry about it.\n\nHow do I decode a MIME/BASE64 string?\nThe MIME::Base64 package handles this as well as the MIME/QP encoding.\nDecoding base 64 becomes as simple as:\n\nuse MIME::Base64;\nmy $decoded = decodebase64($encoded);\n\nThe Email::MIME module can decode base 64-encoded email message parts\ntransparently so the developer doesn't need to worry about it.\n\nHow do I find the user's mail address?\nAsk them for it. There are so many email providers available that it's\nunlikely the local system has any idea how to determine a user's email\naddress.\n\nThe exception is for organization-specific email (e.g.\nfoo@yourcompany.com) where policy can be codified in your program. In\nthat case, you could look at $ENV{USER}, $ENV{LOGNAME}, and getpwuid($<)\nin scalar context, like so:\n\nmy $username = getpwuid($<)\n\nBut you still cannot make assumptions about whether this is correct,\nunless your policy says it is. You really are best off asking the user.\n\nHow do I send email?\nUse the Email::Stuffer module, like so:\n\n# first, create your message\nmy $message = Email::Stuffer->from('you@example.com')\n->to('friend@example.com')\n->subject('Happy birthday!')\n->textbody(\"Happy birthday to you!\\n\");\n\n$message->sendordie;\n\nBy default, Email::Sender::Simple (the \"send\" and \"sendordie\" methods\nuse this under the hood) will try \"sendmail\" first, if it exists in your\n$PATH. This generally isn't the case. If there's a remote mail server\nyou use to send mail, consider investigating one of the Transport\nclasses. At time of writing, the available transports include:\n\nEmail::Sender::Transport::Sendmail\nThis is the default. If you can use the mail(1) or mailx(1) program\nto send mail from the machine where your code runs, you should be\nable to use this.\n\nEmail::Sender::Transport::SMTP\nThis transport contacts a remote SMTP server over TCP. It optionally\nuses TLS or SSL and can authenticate to the server via SASL.\n\nTelling Email::Stuffer to use your transport is straightforward.\n\n$message->transport($emailsendertransportobject)->sendordie;\n\nHow do I use MIME to make an attachment to a mail message?\nEmail::MIME directly supports multipart messages. Email::MIME objects\nthemselves are parts and can be attached to other Email::MIME objects.\nConsult the Email::MIME documentation for more information, including\nall of the supported methods and examples of their use.\n\nEmail::Stuffer uses Email::MIME under the hood to construct messages,\nand wraps the most common attachment tasks with the simple \"attach\" and\n\"attachfile\" methods.\n\nEmail::Stuffer->to('friend@example.com')\n->subject('The file')\n->attachfile('stuff.csv')\n->sendordie;\n\nHow do I read email?\nUse the Email::Folder module, like so:\n\nuse Email::Folder;\n\nmy $folder = Email::Folder->new('/path/to/email/folder');\nwhile(my $message = $folder->nextmessage) {\n# nextmessage returns Email::Simple objects, but we want\n# Email::MIME objects as they're more robust\nmy $mime = Email::MIME->new($message->asstring);\n}\n\nThere are different classes in the Email::Folder namespace for\nsupporting various mailbox types. Note that these modules are generally\nrather limited and only support reading rather than writing.\n\nHow do I 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\nHow can I do RPC in Perl?\nUse one of the RPC modules( <https://metacpan.org/search?q=RPC> ).\n",
                "subsections": []
            }
        }
    }
}