{
    "content": [
        {
            "type": "text",
            "text": "# Re (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** (1 subsections)\n- **Found in /usr/share/perl/5.34/pod/perlfaq4.pod**\n- **Found in /usr/share/perl/5.34/pod/perlfaq5.pod**\n- **Found in /usr/share/perl/5.34/pod/perlfaq6.pod**\n- **Found in /usr/share/perl/5.34/pod/perlfaq7.pod** (1 subsections)\n- **Found in /usr/share/perl/5.34/pod/perlfaq8.pod**\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": "Re",
        "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": 87,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq2.pod",
                "lines": 122,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq3.pod",
                "lines": 307,
                "subsections": [
                    {
                        "name": "mmap",
                        "lines": 88
                    }
                ]
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq4.pod",
                "lines": 966,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq5.pod",
                "lines": 526,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq6.pod",
                "lines": 821,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq7.pod",
                "lines": 427,
                "subsections": [
                    {
                        "name": "local",
                        "lines": 256
                    }
                ]
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq8.pod",
                "lines": 761,
                "subsections": []
            },
            {
                "name": "Found in /usr/share/perl/5.34/pod/perlfaq9.pod",
                "lines": 151,
                "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\nWhat are Perl 4, Perl 5, or Raku (Perl 6)?\nIn short, Perl 4 is the parent to both Perl 5 and Raku (formerly known\nas Perl 6). Perl 5 is the older sibling, and though they are different\nlanguages, someone who knows one will spot many similarities in the\nother.\n\nThe number after Perl (i.e. the 5 after Perl 5) is the major release of\nthe perl interpreter as well as the version of the language. Each major\nversion has significant differences that earlier versions cannot\nsupport.\n\nThe current major release of Perl is Perl 5, first released in 1994. It\ncan run scripts from the previous major release, Perl 4 (March 1991),\nbut has significant differences.\n\nRaku is a reinvention of Perl, a language in the same lineage but not\ncompatible. The two are complementary, not mutually exclusive. Raku is\nnot meant to replace Perl, and vice versa. See \"What is Raku (Perl 6)?\"\nbelow to find out more.\n\nSee perlhist for a history of Perl revisions.\n\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\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\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\nWhat modules and extensions are available for Perl? What is CPAN?\nCPAN stands for Comprehensive Perl Archive Network, a multi-gigabyte\narchive replicated on hundreds of machines all over the world. CPAN\ncontains tens of thousands of modules and extensions, source code and\ndocumentation, designed for *everything* from commercial database\ninterfaces to keyboard/screen control and running large web sites.\n\nYou can search CPAN on <http://metacpan.org>.\n\nThe master web site for CPAN is <http://www.cpan.org/>,\n<http://www.cpan.org/SITES.html> lists all mirrors.\n\nSee the CPAN FAQ at <http://www.cpan.org/misc/cpan-faq.html> for answers\nto the most frequently asked questions about CPAN.\n\nThe Task::Kensho module has a list of recommended modules which you\nshould review as a good starting point.\n\nWhere can I get information on Perl?\n*   <http://www.perl.org/>\n\n*   <http://perldoc.perl.org/>\n\n*   <http://learn.perl.org/>\n\nThe complete Perl documentation is available with the Perl distribution.\nIf you have Perl installed locally, you probably have the documentation\ninstalled as well: type \"perldoc perl\" in a terminal or view online\n<http://perldoc.perl.org/perl.html>.\n\n(Some operating system distributions may ship the documentation in a\ndifferent package; for instance, on Debian, you need to install the\n\"perl-doc\" package.)\n\nMany good books have been written about Perl--see the section later in\nperlfaq2 for more details.\n\nWhere can I post questions?\nThere are many Perl mailing lists for various topics, specifically the\nbeginners list <http://lists.perl.org/list/beginners.html> may be of\nuse.\n\nOther places to ask questions are on the PerlMonks site\n<http://www.perlmonks.org/> or stackoverflow\n<http://stackoverflow.com/questions/tagged/perl>.\n\nWhich Perl blogs should I read?\nPerl News <http://perlnews.org/> covers some of the major events in the\nPerl world, Perl Weekly <http://perlweekly.com/> is a weekly e-mail (and\nRSS feed) of hand-picked Perl articles.\n\n<http://blogs.perl.org/> hosts many Perl blogs, there are also several\nblog aggregators: Perlsphere <http://perlsphere.net/> and IronMan\n<http://ironman.enlightenedperl.org/> are two of them.\n\nWhat mailing lists are there for Perl?\nA comprehensive list of Perl-related mailing lists can be found at\n<http://lists.perl.org/>\n\nWhere can I buy a commercial version of Perl?\nPerl already *is* commercial software: it has a license that you can\ngrab and carefully read to your manager. It is distributed in releases\nand comes in well-defined packages. There is a very large and supportive\nuser community and an extensive literature.\n\nIf you still need commercial support ActiveState\n<http://www.activestate.com/activeperl> offers this.\n\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 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 cross-reference my Perl programs?\nThe B::Xref module can be used to generate cross-reference reports for\nPerl programs.\n\nperl -MO=Xref[,OPTIONS] scriptname.plx\n\nIs there a pretty-printer (formatter) for Perl?\nPerl::Tidy comes with a perl script perltidy which indents and reformats\nPerl scripts to make them easier to read by trying to follow the rules\nof the perlstyle. If you write Perl, or spend much time reading Perl,\nyou will probably find it useful.\n\nOf course, if you simply follow the guidelines in perlstyle, you\nshouldn't need to reformat. The habit of formatting your code as you\nwrite it will help prevent bugs. Your editor can and should help you\nwith this. The perl-mode or newer cperl-mode for emacs can provide\nremarkable amounts of help with most (but not all) code, and even less\nprogrammable editors can provide significant assistance. Tom\nChristiansen and many other VI users swear by the following settings in\nvi and its clones:\n\nset ai sw=4\nmap! ^O {^M}^[O^T\n\nPut that in your .exrc file (replacing the caret characters with control\ncharacters) and away you go. In insert mode, ^T is for indenting, ^D is\nfor undenting, and ^O is for blockdenting--as it were. A more complete\nexample, with comments, can be found at\n<http://www.cpan.org/authors/id/T/TO/TOMC/scripts/toms.exrc.gz>\n\nIs there an IDE or Windows Perl Editor?\nPerl programs are just plain text, so any editor will do.\n\nIf you're on Unix, you already have an IDE--Unix itself. The Unix\nphilosophy is the philosophy of several small tools that each do one\nthing and do it well. It's like a carpenter's toolbox.\n\nIf you want an IDE, check the following (in alphabetical order, not\norder of preference):\n\nEclipse\n<http://e-p-i-c.sf.net/>\n\nThe Eclipse Perl Integration Project integrates Perl\nediting/debugging with Eclipse.\n\nEnginsite\n<http://www.enginsite.com/>\n\nPerl Editor by EngInSite is a complete integrated development\nenvironment (IDE) for creating, testing, and debugging Perl scripts;\nthe tool runs on Windows 9x/NT/2000/XP or later.\n\nIntelliJ IDEA\n<https://plugins.jetbrains.com/plugin/7796>\n\nCamelcade plugin provides Perl5 support in IntelliJ IDEA and other\nJetBrains IDEs.\n\nKephra\n<http://kephra.sf.net>\n\nGUI editor written in Perl using wxWidgets and Scintilla with lots\nof smaller features. Aims for a UI based on Perl principles like\nTIMTOWTDI and \"easy things should be easy, hard things should be\npossible\".\n\nKomodo\n<http://www.ActiveState.com/Products/Komodo/>\n\nActiveState's cross-platform (as of October 2004, that's Windows,\nLinux, and Solaris), multi-language IDE has Perl support, including\na regular expression debugger and remote debugging.\n\nNotepad++\n<http://notepad-plus.sourceforge.net/>\n\nOpen Perl IDE\n<http://open-perl-ide.sourceforge.net/>\n\nOpen Perl IDE is an integrated development environment for writing\nand debugging Perl scripts with ActiveState's ActivePerl\ndistribution under Windows 95/98/NT/2000.\n\nOptiPerl\n<http://www.optiperl.com/>\n\nOptiPerl is a Windows IDE with simulated CGI environment, including\ndebugger and syntax-highlighting editor.\n\nPadre\n<http://padre.perlide.org/>\n\nPadre is cross-platform IDE for Perl written in Perl using wxWidgets\nto provide a native look and feel. It's open source under the\nArtistic License. It is one of the newer Perl IDEs.\n\nPerlBuilder\n<http://www.solutionsoft.com/perl.htm>\n\nPerlBuilder is an integrated development environment for Windows\nthat supports Perl development.\n\nvisiPerl+\n<http://helpconsulting.net/visiperl/index.html>\n\nFrom Help Consulting, for Windows.\n\nVisual Perl\n<http://www.activestate.com/Products/VisualPerl/>\n\nVisual Perl is a Visual Studio.NET plug-in from ActiveState.\n\nZeus\n<http://www.zeusedit.com/lookmain.html>\n\nZeus for Windows is another Win32 multi-language editor/IDE that\ncomes with support for Perl.\n\nFor editors: if you're on Unix you probably have vi or a vi clone\nalready, and possibly an emacs too, so you may not need to download\nanything. In any emacs the cperl-mode (M-x cperl-mode) gives you perhaps\nthe best available Perl editing mode in any editor.\n\nIf you are using Windows, you can use any editor that lets you work with\nplain text, such as NotePad or WordPad. Word processors, such as\nMicrosoft Word or WordPerfect, typically do not work since they insert\nall sorts of behind-the-scenes information, although some allow you to\nsave files as \"Text Only\". You can also download text editors designed\nspecifically for programming, such as Textpad (\n<http://www.textpad.com/> ) and UltraEdit ( <http://www.ultraedit.com/>\n), among others.\n\nIf you are using MacOS, the same concerns apply. MacPerl (for Classic\nenvironments) comes with a simple editor. Popular external editors are\nBBEdit ( <http://www.barebones.com/products/bbedit/> ) or Alpha (\n<http://www.his.com/~jguyer/Alpha/Alpha8.html> ). MacOS X users can use\nUnix editors as well.\n\nGNU Emacs\n<http://www.gnu.org/software/emacs/windows/ntemacs.html>\n\nMicroEMACS\n<http://www.microemacs.de/>\n\nXEmacs\n<http://www.xemacs.org/Download/index.html>\n\nJed <http://space.mit.edu/~davis/jed/>\n\nor a vi clone such as\n\nVim <http://www.vim.org/>\n\nVile\n<http://invisible-island.net/vile/vile.html>\n\nThe following are Win32 multilanguage editor/IDEs that support Perl:\n\nMultiEdit\n<http://www.MultiEdit.com/>\n\nSlickEdit\n<http://www.slickedit.com/>\n\nConTEXT\n<http://www.contexteditor.org/>\n\nThere is also a toyedit Text widget based editor written in Perl that is\ndistributed with the Tk module on CPAN. The ptkdb (\n<http://ptkdb.sourceforge.net/> ) is a Perl/Tk-based debugger that acts\nas a development environment of sorts. Perl Composer (\n<http://perlcomposer.sourceforge.net/> ) is an IDE for Perl/Tk GUI\ncreation.\n\nIn addition to an editor/IDE you might be interested in a more powerful\nshell environment for Win32. Your options include\n\nbash\nfrom the Cygwin package ( <http://cygwin.com/> )\n\nzsh <http://www.zsh.org/>\n\nCygwin is covered by the GNU General Public License (but that shouldn't\nmatter for Perl use). Cygwin contains (in addition to the shell) a\ncomprehensive set of standard Unix toolkit utilities.\n\nBBEdit and TextWrangler\nare text editors for OS X that have a Perl sensitivity mode (\n<http://www.barebones.com/> ).\n\nWhere can I get Perl macros for vi?\nFor a complete version of Tom Christiansen's vi configuration file, see\n<http://www.cpan.org/authors/id/T/TO/TOMC/scripts/toms.exrc.gz> , the\nstandard benchmark file for vi emulators. The file runs best with nvi,\nthe current version of vi out of Berkeley, which incidentally can be\nbuilt with an embedded Perl interpreter--see\n<http://www.cpan.org/src/misc/> .\n\nWhere can I get perl-mode or cperl-mode for emacs?\nSince Emacs version 19 patchlevel 22 or so, there have been both a\nperl-mode.el and support for the Perl debugger built in. These should\ncome with the standard Emacs 19 distribution.\n\nNote that the perl-mode of emacs will have fits with \"main'foo\" (single\nquote), and mess up the indentation and highlighting. You are probably\nusing \"main::foo\" in new Perl code anyway, so this shouldn't be an\nissue.\n\nFor CPerlMode, see <http://www.emacswiki.org/cgi-bin/wiki/CPerlMode>\n\nIs it safe to return a reference to local or lexical data?\nYes. Perl's garbage collection system takes care of this so everything\nworks out right.\n\nsub makeone {\nmy @a = ( 1 .. 10 );\nreturn \\@a;\n}\n\nfor ( 1 .. 10 ) {\npush @many, makeone();\n}\n\nprint $many[4][5], \"\\n\";\n\nprint \"@many\\n\";\n\nHow can I free an array or hash so my program shrinks?\n(contributed by Michael Carman)\n\nYou usually can't. Memory allocated to lexicals (i.e. my() variables)\ncannot be reclaimed or reused even if they go out of scope. It is\nreserved in case the variables come back into scope. Memory allocated to\nglobal variables can be reused (within your program) by using undef()\nand/or delete().\n\nOn most operating systems, memory allocated to a program can never be\nreturned to the system. That's why long-running programs sometimes re-\nexec themselves. Some operating systems (notably, systems that use",
                "subsections": [
                    {
                        "name": "mmap",
                        "content": "is no longer used, but on such systems, perl must be configured and\ncompiled to use the OS's malloc, not perl's.\n\nIn general, memory allocation and de-allocation isn't something you can\nor should be worrying about much in Perl.\n\nSee also \"How can I make my Perl program take less memory?\"\n\nHow can I make my CGI script more efficient?\nBeyond the normal measures described to make general Perl programs\nfaster or smaller, a CGI program has additional issues. It may be run\nseveral times per second. Given that each time it runs it will need to\nbe re-compiled and will often allocate a megabyte or more of system\nmemory, this can be a killer. Compiling into C isn't going to help you\nbecause the process start-up overhead is where the bottleneck is.\n\nThere are three popular ways to avoid this overhead. One solution\ninvolves running the Apache HTTP server (available from\n<http://www.apache.org/> ) with either of the modperl or modfastcgi\nplugin modules.\n\nWith modperl and the Apache::Registry module (distributed with\nmodperl), httpd will run with an embedded Perl interpreter which\npre-compiles your script and then executes it within the same address\nspace without forking. The Apache extension also gives Perl access to\nthe internal server API, so modules written in Perl can do just about\nanything a module written in C can. For more on modperl, see\n<http://perl.apache.org/>\n\nWith the FCGI module (from CPAN) and the modfastcgi module (available\nfrom <http://www.fastcgi.com/> ) each of your Perl programs becomes a\npermanent CGI daemon process.\n\nFinally, Plack is a Perl module and toolkit that contains PSGI\nmiddleware, helpers and adapters to web servers, allowing you to easily\ndeploy scripts which can continue running, and provides flexibility with\nregards to which web server you use. It can allow existing CGI scripts\nto enjoy this flexibility and performance with minimal changes, or can\nbe used along with modern Perl web frameworks to make writing and\ndeploying web services with Perl a breeze.\n\nThese solutions can have far-reaching effects on your system and on the\nway you write your CGI programs, so investigate them with care.\n\nSee also\n<http://www.cpan.org/modules/by-category/15WorldWideWebHTMLHTTPCGI\n/> .\n\nWhere can I learn about CGI or Web programming in Perl?\nFor modules, get the CGI or LWP modules from CPAN. For textbooks, see\nthe two especially dedicated to web stuff in the question on books. For\nproblems and questions related to the web, like \"Why do I get 500\nErrors\" or \"Why doesn't it run from the browser right when it runs fine\non the command line\", see the troubleshooting guides and references in\nperlfaq9 or in the CGI MetaFAQ:\n\nL<http://www.perl.org/CGIMetaFAQ.html>\n\nLooking into <https://plackperl.org> and modern Perl web frameworks is\nhighly recommended, though; web programming in Perl has evolved a long\nway from the old days of simple CGI scripts.\n\nWhere can I learn about object-oriented Perl programming?\nA good place to start is perlootut, and you can use perlobj for\nreference.\n\nA good book on OO on Perl is the \"Object-Oriented Perl\" by Damian Conway\nfrom Manning Publications, or \"Intermediate Perl\" by Randal Schwartz,\nbrian d foy, and Tom Phoenix from O'Reilly Media.\n\nWhere can I learn about linking C with Perl?\nIf you want to call C from Perl, start with perlxstut, moving on to\nperlxs, xsubpp, and perlguts. If you want to call Perl from C, then read\nperlembed, perlcall, and perlguts. Don't forget that you can learn a lot\nfrom looking at how the authors of existing extension modules wrote\ntheir code and solved their problems.\n\nYou might not need all the power of XS. The Inline::C module lets you\nput C code directly in your Perl source. It handles all the magic to\nmake it work. You still have to learn at least some of the perl API but\nyou won't have to deal with the complexity of the XS support files.\n\nI've read perlembed, perlguts, etc., but I can't embed perl in my C program; what am I doing wrong?\nDownload the ExtUtils::Embed kit from CPAN and run `make test'. If the\ntests pass, read the pods again and again and again. If they fail,\nsubmit a bug report to <https://github.com/Perl/perl5/issues> with the\noutput of \"make test TESTVERBOSE=1\" along with \"perl -V\".\n"
                    }
                ]
            },
            "Found in /usr/share/perl/5.34/pod/perlfaq4.pod": {
                "content": "Why 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\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 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 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 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 reverse a string?\nUse \"reverse()\" in scalar context, as documented in \"reverse\" in\nperlfunc.\n\nmy $reversed = reverse $string;\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 can I count the number of occurrences of a substring within a string?\nThere are a number of ways, with varying efficiency. If you want a count\nof a certain single character (X) within a string, you can use the\n\"tr///\" function like so:\n\nmy $string = \"ThisXlineXhasXsomeXx'sXinXit\";\nmy $count = ($string =~ tr/X//);\nprint \"There are $count X characters in the string\";\n\nThis is fine if you are just looking for a single character. However, if\nyou are trying to count multiple character substrings within a larger\nstring, \"tr///\" won't work. What you can do is wrap a while() loop\naround a global pattern match. For example, let's count negative\nintegers:\n\nmy $string = \"-9 55 48 -2 23 -76 4 14 -44\";\nmy $count = 0;\nwhile ($string =~ /-\\d+/g) { $count++ }\nprint \"There are $count negative numbers in the string\";\n\nAnother version uses a global match in list context, then assigns the\nresult to a scalar, producing a count of the number of matches.\n\nmy $count = () = $string =~ /-\\d+/g;\n\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 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\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\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 can I know how many entries are in a hash?\n(contributed by brian d foy)\n\nThis is very similar to \"How do I process an entire hash?\", also in\nperlfaq4, but a bit simpler in the common cases.\n\nYou can use the \"keys()\" built-in function in scalar context to find out\nhave many entries you have in a hash:\n\nmy $keycount = keys %hash; # must be scalar context!\n\nIf you want to find out how many entries have a defined value, that's a\nbit different. You have to check each value. A \"grep\" is handy:\n\nmy $definedvaluecount = grep { defined } values %hash;\n\nYou can use that same structure to count the entries any way that you\nlike. If you want the count of the keys with vowels in them, you just\ntest for that instead:\n\nmy $vowelcount = grep { /[aeiou]/ } keys %hash;\n\nThe \"grep\" in scalar context returns the count. If you want the list of\nmatching items, just use it in list context instead:\n\nmy @definedvalues = grep { defined } values %hash;\n\nThe \"keys()\" function also resets the iterator, which means that you may\nsee strange results if you use this between uses of other hash operators\nsuch as \"each()\".\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\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 make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?\nUsually a hash ref, perhaps like this:\n\n$record = {\nNAME   => \"Jason\",\nEMPNO  => 132,\nTITLE  => \"deputy peon\",\nAGE    => 23,\nSALARY => 37000,\nPALS   => [ \"Norbert\", \"Rhys\", \"Phineas\"],\n};\n\nReferences are documented in perlref and perlreftut. Examples of complex\ndata structures are given in perldsc and perllol. Examples of structures\nand object-oriented classes are in perlootut.\n\nHow can I use a reference as a hash key?\n(contributed by brian d foy and Ben Morrow)\n\nHash keys are strings, so you can't really use a reference as the key.\nWhen you try to do that, perl turns the reference into its stringified\nform (for instance, \"HASH(0xDEADBEEF)\"). From there you can't get back\nthe reference from the stringified form, at least without doing some\nextra work on your own.\n\nRemember that the entry in the hash will still be there even if the\nreferenced variable goes out of scope, and that it is entirely possible\nfor Perl to subsequently allocate a different variable at the same\naddress. This will mean a new variable might accidentally be associated\nwith the value for an old.\n\nIf you have Perl 5.10 or later, and you just want to store a value\nagainst the reference for lookup later, you can use the core\nHash::Util::Fieldhash module. This will also handle renaming the keys if\nyou use multiple threads (which causes all variables to be reallocated\nat new addresses, changing their stringification), and\ngarbage-collecting the entries when the referenced variable goes out of\nscope.\n\nIf you actually need to be able to get a real reference back from each\nhash entry, you can use the Tie::RefHash module, which does the required\nwork for you.\n\nHow can I 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 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 verify a credit card checksum?\nGet the Business::CreditCard module from CPAN.\n",
                "subsections": []
            },
            "Found in /usr/share/perl/5.34/pod/perlfaq5.pod": {
                "content": "How 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 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 come when I open a file read-write it wipes it out?\nBecause you're using something like this, which truncates the file\n*then* gives you read-write access:\n\nopen my $fh, '+>', '/path/name'; # WRONG (almost always)\n\nWhoops. You should instead use this, which will fail if the file doesn't\nexist:\n\nopen my $fh, '+<', '/path/name'; # open for update\n\nUsing \">\" always clobbers or creates. Using \"<\" never does either. The\n\"+\" doesn't change this.\n\nHere are examples of many kinds of file opens. Those using \"sysopen\" all\nassume that you've pulled in the constants from Fcntl:\n\nuse Fcntl;\n\nTo open file for reading:\n\nopen my $fh, '<', $path                               or die $!;\nsysopen my $fh, $path, ORDONLY                       or die $!;\n\nTo open file for writing, create new file if needed or else truncate old\nfile:\n\nopen my $fh, '>', $path                               or die $!;\nsysopen my $fh, $path, OWRONLY|OTRUNC|OCREAT       or die $!;\nsysopen my $fh, $path, OWRONLY|OTRUNC|OCREAT, 0666 or die $!;\n\nTo open file for writing, create new file, file must not exist:\n\nsysopen my $fh, $path, OWRONLY|OEXCL|OCREAT        or die $!;\nsysopen my $fh, $path, OWRONLY|OEXCL|OCREAT, 0666  or die $!;\n\nTo open file for appending, create if necessary:\n\nopen my $fh, '>>', $path                              or die $!;\nsysopen my $fh, $path, OWRONLY|OAPPEND|OCREAT      or die $!;\nsysopen my $fh, $path, OWRONLY|OAPPEND|OCREAT, 0666 or die $!;\n\nTo open file for appending, file must exist:\n\nsysopen my $fh, $path, OWRONLY|OAPPEND              or die $!;\n\nTo open file for update, file must exist:\n\nopen my $fh, '+<', $path                              or die $!;\nsysopen my $fh, $path, ORDWR                         or die $!;\n\nTo open file for update, create file if necessary:\n\nsysopen my $fh, $path, ORDWR|OCREAT                 or die $!;\nsysopen my $fh, $path, ORDWR|OCREAT, 0666           or die $!;\n\nTo open file for update, file must not exist:\n\nsysopen my $fh, $path, ORDWR|OEXCL|OCREAT          or die $!;\nsysopen my $fh, $path, ORDWR|OEXCL|OCREAT, 0666    or die $!;\n\nTo open a file without blocking, creating if necessary:\n\nsysopen my $fh, '/foo/somefile', OWRONLY|ONDELAY|OCREAT\nor die \"can't open /foo/somefile: $!\":\n\nBe warned that neither creation nor deletion of files is guaranteed to\nbe an atomic operation over NFS. That is, two processes might both\nsuccessfully create or unlink the same file! Therefore OEXCL isn't as\nexclusive as you might wish.\n\nSee also perlopentut.\n\nHow can I reliably rename a file?\nIf your operating system supports a proper mv(1) utility or its\nfunctional equivalent, this works:\n\nrename($old, $new) or system(\"mv\", $old, $new);\n\nIt may be more portable to use the File::Copy module instead. You just\ncopy to the new file to the new name (checking return values), then\ndelete the old one. This isn't really the same semantically as a\n\"rename()\", which preserves meta-information like permissions,\ntimestamps, inode info, etc.\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\nHow 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\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 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",
                "subsections": []
            },
            "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\nI'm having trouble matching over more than one line. What's wrong?\nEither you don't have more than one line in the string you're looking at\n(probably), or else you aren't using the correct modifier(s) on your\npattern (possibly).\n\nThere are many ways to get multiline data into a string. If you want it\nto happen automatically while reading input, you'll want to set $/\n(probably to '' for paragraphs or \"undef\" for the whole file) to allow\nyou to read more than one line at a time.\n\nRead perlre to help you decide which of \"/s\" and \"/m\" (or both) you\nmight want to use: \"/s\" allows dot to include newline, and \"/m\" allows\ncaret and dollar to match next to a newline, not just at the end of the\nstring. You do need to make sure that you've actually got a multiline\nstring in there.\n\nFor example, this program detects duplicate words, even when they span\nline breaks (but not paragraph ones). For this example, we don't need\n\"/s\" because we aren't using dot in a regular expression that we want to\ncross line boundaries. Neither do we need \"/m\" because we don't want\ncaret or dollar to match at any point inside the record next to\nnewlines. But it's imperative that $/ be set to something other than the\ndefault, or else we won't actually ever have a multiline record read in.\n\n$/ = '';          # read in whole paragraph, not just one line\nwhile ( <> ) {\nwhile ( /\\b([\\w'-]+)(\\s+\\g1)+\\b/gi ) {     # word starts alpha\nprint \"Duplicate $1 at paragraph $.\\n\";\n}\n}\n\nHere's some code that finds sentences that begin with \"From \" (which\nwould be mangled by many mailers):\n\n$/ = '';          # read in whole paragraph, not just one line\nwhile ( <> ) {\nwhile ( /^From /gm ) { # /m makes ^ match next to \\n\nprint \"leading From in paragraph $.\\n\";\n}\n}\n\nHere's code that finds everything between START and END in a paragraph:\n\nundef $/;          # read in whole file, not just one line or paragraph\nwhile ( <> ) {\nwhile ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries\nprint \"$1\\n\";\n}\n}\n\nHow can I pull out lines between two patterns that are themselves on different lines?\nYou can use Perl's somewhat exotic \"..\" operator (documented in perlop):\n\nperl -ne 'print if /START/ .. /END/' file1 file2 ...\n\nIf you wanted text and not lines, you would use\n\nperl -0777 -ne 'print \"$1\\n\" while /START(.*?)END/gs' file1 file2 ...\n\nBut if you want nested occurrences of \"START\" through \"END\", you'll run\nup against the problem described in the question in this section on\nmatching balanced text.\n\nHere's another example of using \"..\":\n\nwhile (<>) {\nmy $inheader =   1  .. /^$/;\nmy $inbody   = /^$/ .. eof;\n# now choose between them\n} continue {\n$. = 0 if eof;    # fix $.\n}\n\nHow do I match XML, HTML, or other nasty, ugly things with a regex?\nDo not use regexes. Use a module and forget about the regular\nexpressions. The XML::LibXML, HTML::TokeParser and HTML::TreeBuilder\nmodules are good starts, although each namespace has other parsing\nmodules specialized for certain tasks and different ways of doing it.\nStart at CPAN Search ( <http://metacpan.org/> ) and wonder at all the\nwork people have done for you already! :)\n\nI put a regular expression into $/ but it didn't work. What's wrong?\n$/ has to be a string. You can use these examples if you really need to\ndo this.\n\nIf you have File::Stream, this is easy.\n\nuse File::Stream;\n\nmy $stream = File::Stream->new(\n$filehandle,\nseparator => qr/\\s*,\\s*/,\n);\n\nprint \"$\\n\" while <$stream>;\n\nIf you don't have File::Stream, you have to do a little more work.\n\nYou can use the four-argument form of sysread to continually add to a\nbuffer. After you add to the buffer, you check if you have a complete\nline (using your regular expression).\n\nlocal $ = \"\";\nwhile( sysread FH, $, 8192, length ) {\nwhile( s/^((?s).*?)yourpattern// ) {\nmy $record = $1;\n# do stuff here.\n}\n}\n\nYou can do the same thing with foreach and a match using the c flag and\nthe \\G anchor, if you do not mind your entire file being in memory at\nthe end.\n\nlocal $ = \"\";\nwhile( sysread FH, $, 8192, length ) {\nforeach my $record ( m/\\G((?s).*?)yourpattern/gc ) {\n# do stuff here.\n}\nsubstr( $, 0, pos ) = \"\" if pos;\n}\n\nHow do I substitute case-insensitively on the LHS while preserving case on the RHS?\nHere's a lovely Perlish solution by Larry Rosler. It exploits properties\nof bitwise xor on ASCII strings.\n\n$= \"this is a TEsT case\";\n\n$old = 'test';\n$new = 'success';\n\ns{(\\Q$old\\E)}\n{ uc $new | (uc $1 ^ $1) .\n(uc(substr $1, -1) ^ substr $1, -1) x\n(length($new) - length $1)\n}egi;\n\nprint;\n\nAnd here it is as a subroutine, modeled after the above:\n\nsub preservecase {\nmy ($old, $new) = @;\nmy $mask = uc $old ^ $old;\n\nuc $new | $mask .\nsubstr($mask, -1) x (length($new) - length($old))\n}\n\n$string = \"this is a TEsT case\";\n$string =~ s/(test)/preservecase($1, \"success\")/egi;\nprint \"$string\\n\";\n\nThis prints:\n\nthis is a SUcCESS case\n\nAs an alternative, to keep the case of the replacement word if it is\nlonger than the original, you can use this code, by Jeff Pinyan:\n\nsub preservecase {\nmy ($from, $to) = @;\nmy ($lf, $lt) = map length, @;\n\nif ($lt < $lf) { $from = substr $from, 0, $lt }\nelse { $from .= substr $to, $lf }\n\nreturn uc $to | ($from ^ uc $from);\n}\n\nThis changes the sentence to \"this is a SUcCess case.\"\n\nJust to show that C programmers can write C in any programming language,\nif you prefer a more C-like solution, the following script makes the\nsubstitution have the same case, letter by letter, as the original. (It\nalso happens to run about 240% slower than the Perlish solution runs.)\nIf the substitution has more characters than the string being\nsubstituted, the case of the last character is used for the rest of the\nsubstitution.\n\n# Original by Nathan Torkington, massaged by Jeffrey Friedl\n#\nsub preservecase\n{\nmy ($old, $new) = @;\nmy $state = 0; # 0 = no change; 1 = lc; 2 = uc\nmy ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));\nmy $len = $oldlen < $newlen ? $oldlen : $newlen;\n\nfor ($i = 0; $i < $len; $i++) {\nif ($c = substr($old, $i, 1), $c =~ /[\\W\\d]/) {\n$state = 0;\n} elsif (lc $c eq $c) {\nsubstr($new, $i, 1) = lc(substr($new, $i, 1));\n$state = 1;\n} else {\nsubstr($new, $i, 1) = uc(substr($new, $i, 1));\n$state = 2;\n}\n}\n# finish up with any remaining new (for when new is longer than old)\nif ($newlen > $oldlen) {\nif ($state == 1) {\nsubstr($new, $oldlen) = lc(substr($new, $oldlen));\n} elsif ($state == 2) {\nsubstr($new, $oldlen) = uc(substr($new, $oldlen));\n}\n}\nreturn $new;\n}\n\nHow can I quote a variable to use in a regex?\nThe Perl parser will expand $variable and @variable references in\nregular expressions unless the delimiter is a single quote. Remember,\ntoo, that the right-hand side of a \"s///\" substitution is considered a\ndouble-quoted string (see perlop for more details). Remember also that\nany regex special characters will be acted on unless you precede the\nsubstitution with \\Q. Here's an example:\n\n$string = \"Placido P. Octopus\";\n$regex  = \"P.\";\n\n$string =~ s/$regex/Polyp/;\n# $string is now \"Polypacido P. Octopus\"\n\nBecause \".\" is special in regular expressions, and can match any single\ncharacter, the regex \"P.\" here has matched the <Pl> in the original\nstring.\n\nTo escape the special meaning of \".\", we use \"\\Q\":\n\n$string = \"Placido P. Octopus\";\n$regex  = \"P.\";\n\n$string =~ s/\\Q$regex/Polyp/;\n# $string is now \"Placido Polyp Octopus\"\n\nThe use of \"\\Q\" causes the \".\" in the regex to be treated as a regular\ncharacter, so that \"P.\" matches a \"P\" followed by a dot.\n\nWhat is \"/o\" really for?\n(contributed by brian d foy)\n\nThe \"/o\" option for regular expressions (documented in perlop and\nperlreref) tells Perl to compile the regular expression only once. This\nis only useful when the pattern contains a variable. Perls 5.6 and later\nhandle this automatically if the pattern does not change.\n\nSince the match operator \"m//\", the substitution operator \"s///\", and\nthe regular expression quoting operator \"qr//\" are double-quotish\nconstructs, you can interpolate variables into the pattern. See the\nanswer to \"How can I quote a variable to use in a regex?\" for more\ndetails.\n\nThis example takes a regular expression from the argument list and\nprints the lines of input that match it:\n\nmy $pattern = shift @ARGV;\n\nwhile( <> ) {\nprint if m/$pattern/;\n}\n\nVersions of Perl prior to 5.6 would recompile the regular expression for\neach iteration, even if $pattern had not changed. The \"/o\" would prevent\nthis by telling Perl to compile the pattern the first time, then reuse\nthat for subsequent iterations:\n\nmy $pattern = shift @ARGV;\n\nwhile( <> ) {\nprint if m/$pattern/o; # useful for Perl < 5.6\n}\n\nIn versions 5.6 and later, Perl won't recompile the regular expression\nif the variable hasn't changed, so you probably don't need the \"/o\"\noption. It doesn't hurt, but it doesn't help either. If you want any\nversion of Perl to compile the regular expression only once even if the\nvariable changes (thus, only using its initial value), you still need\nthe \"/o\".\n\nYou can watch Perl's regular expression engine at work to verify for\nyourself if Perl is recompiling a regular expression. The \"use re\n'debug'\" pragma (comes with Perl 5.005 and later) shows the details.\nWith Perls before 5.6, you should see \"re\" reporting that its compiling\nthe regular expression on each iteration. With Perl 5.6 or later, you\nshould only see \"re\" report that for the first iteration.\n\nuse re 'debug';\n\nmy $regex = 'Perl';\nforeach ( qw(Perl Java Ruby Python) ) {\nprint STDERR \"-\" x 73, \"\\n\";\nprint STDERR \"Trying $...\\n\";\nprint STDERR \"\\t$ is good!\\n\" if m/$regex/;\n}\n\nHow do I use a regular expression to strip C-style comments from a file?\nWhile this actually can be done, it's much harder than you'd think. For\nexample, this one-liner\n\nperl -0777 -pe 's{/\\*.*?\\*/}{}gs' foo.c\n\nwill work in many but not all cases. You see, it's too simple-minded for\ncertain kinds of C programs, in particular, those with what appear to be\ncomments in quoted strings. For that, you'd need something like this,\ncreated by Jeffrey Friedl and later modified by Fred Curtis.\n\n$/ = undef;\n$ = <>;\ns#/\\*[^*]*\\*+([^/*][^*]*\\*+)*/|(\"(\\\\.|[^\"\\\\])*\"|'(\\\\.|[^'\\\\])*'|.[^/\"'\\\\]*)#defined $2 ? $2 : \"\"#gse;\nprint;\n\nThis could, of course, be more legibly written with the \"/x\" modifier,\nadding whitespace and comments. Here it is expanded, courtesy of Fred\nCurtis.\n\ns{\n/\\*         ##  Start of /* ... */ comment\n[^*]*\\*+    ##  Non-* followed by 1-or-more *'s\n(\n[^/*][^*]*\\*+\n)*          ##  0-or-more things which don't start with /\n##    but do end with '*'\n/           ##  End of /* ... */ comment\n\n|         ##     OR  various things which aren't comments:\n\n(\n\"           ##  Start of \" ... \" string\n(\n\\\\.           ##  Escaped char\n|               ##    OR\n[^\"\\\\]        ##  Non \"\\\n)*\n\"           ##  End of \" ... \" string\n\n|         ##     OR\n\n'           ##  Start of ' ... ' string\n(\n\\\\.           ##  Escaped char\n|               ##    OR\n[^'\\\\]        ##  Non '\\\n)*\n'           ##  End of ' ... ' string\n\n|         ##     OR\n\n.           ##  Anything other char\n[^/\"'\\\\]*   ##  Chars which doesn't start a comment, string or escape\n)\n}{defined $2 ? $2 : \"\"}gxse;\n\nA slight modification also removes C++ comments, possibly spanning\nmultiple lines using a continuation character:\n\ns#/\\*[^*]*\\*+([^/*][^*]*\\*+)*/|//([^\\\\]|[^\\n][\\n]?)*?\\n|(\"(\\\\.|[^\"\\\\])*\"|'(\\\\.|[^'\\\\])*'|.[^/\"'\\\\]*)#defined $3 ? $3 : \"\"#gse;\n\nCan I use Perl regular expressions to match balanced text?\n(contributed by brian d foy)\n\nYour first try should probably be the Text::Balanced module, which is in\nthe Perl standard library since Perl 5.8. It has a variety of functions\nto deal with tricky text. The Regexp::Common module can also help by\nproviding canned patterns you can use.\n\nAs of Perl 5.10, you can match balanced text with regular expressions\nusing recursive patterns. Before Perl 5.10, you had to resort to various\ntricks such as using Perl code in \"(??{})\" sequences.\n\nHere's an example using a recursive regular expression. The goal is to\ncapture all of the text within angle brackets, including the text in\nnested angle brackets. This sample text has two \"major\" groups: a group\nwith one level of nesting and a group with two levels of nesting. There\nare five total groups in angle brackets:\n\nI have some <brackets in <nested brackets> > and\n<another group <nested once <nested twice> > >\nand that's it.\n\nThe regular expression to match the balanced text uses two new (to Perl\n5.10) regular expression features. These are covered in perlre and this\nexample is a modified version of one in that documentation.\n\nFirst, adding the new possessive \"+\" to any quantifier finds the longest\nmatch and does not backtrack. That's important since you want to handle\nany angle brackets through the recursion, not backtracking. The group\n\"[^<>]++\" finds one or more non-angle brackets without backtracking.\n\nSecond, the new \"(?PARNO)\" refers to the sub-pattern in the particular\ncapture group given by \"PARNO\". In the following regex, the first\ncapture group finds (and remembers) the balanced text, and you need that\nsame pattern within the first buffer to get past the nested text. That's\nthe recursive part. The \"(?1)\" uses the pattern in the outer capture\ngroup as an independent part of the regex.\n\nPutting it all together, you have:\n\n#!/usr/local/bin/perl5.10.0\n\nmy $string =<<\"HERE\";\nI have some <brackets in <nested brackets> > and\n<another group <nested once <nested twice> > >\nand that's it.\nHERE\n\nmy @groups = $string =~ m/\n(                   # start of capture group 1\n<                   # match an opening angle bracket\n(?:\n[^<>]++     # one or more non angle brackets, non backtracking\n|\n(?1)        # found < or >, so recurse to capture group 1\n)*\n>                   # match a closing angle bracket\n)                   # end of capture group 1\n/xg;\n\n$\" = \"\\n\\t\";\nprint \"Found:\\n\\t@groups\\n\";\n\nThe output shows that Perl found the two major groups:\n\nFound:\n<brackets in <nested brackets> >\n<another group <nested once <nested twice> > >\n\nWith a little extra work, you can get all of the groups in angle\nbrackets even if they are in other angle brackets too. Each time you get\na balanced match, remove its outer delimiter (that's the one you just\nmatched so don't match it again) and add it to a queue of strings to\nprocess. Keep doing that until you get no matches:\n\n#!/usr/local/bin/perl5.10.0\n\nmy @queue =<<\"HERE\";\nI have some <brackets in <nested brackets> > and\n<another group <nested once <nested twice> > >\nand that's it.\nHERE\n\nmy $regex = qr/\n(                   # start of bracket 1\n<                   # match an opening angle bracket\n(?:\n[^<>]++     # one or more non angle brackets, non backtracking\n|\n(?1)        # recurse to bracket 1\n)*\n>                   # match a closing angle bracket\n)                   # end of bracket 1\n/x;\n\n$\" = \"\\n\\t\";\n\nwhile( @queue ) {\nmy $string = shift @queue;\n\nmy @groups = $string =~ m/$regex/g;\nprint \"Found:\\n\\t@groups\\n\\n\" if @groups;\n\nunshift @queue, map { s/^<//; s/>$//; $ } @groups;\n}\n\nThe output shows all of the groups. The outermost matches show up first\nand the nested matches show up later:\n\nFound:\n<brackets in <nested brackets> >\n<another group <nested once <nested twice> > >\n\nFound:\n<nested brackets>\n\nFound:\n<nested once <nested twice> >\n\nFound:\n<nested twice>\n\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 can I print out a word-frequency or line-frequency summary?\nTo do this, you have to parse out each word in the input stream. We'll\npretend that by word you mean chunk of alphabetics, hyphens, or\napostrophes, rather than the non-whitespace chunk idea of a word given\nin the previous question:\n\nmy (%seen);\nwhile (<>) {\nwhile ( /(\\b[^\\W\\d][\\w'-]+\\b)/g ) {   # misses \"`sheep'\"\n$seen{$1}++;\n}\n}\n\nwhile ( my ($word, $count) = each %seen ) {\nprint \"$count $word\\n\";\n}\n\nIf you wanted to do the same thing for lines, you wouldn't need a\nregular expression:\n\nmy (%seen);\n\nwhile (<>) {\n$seen{$}++;\n}\n\nwhile ( my ($line, $count) = each %seen ) {\nprint \"$count $line\";\n}\n\nIf you want these output in a sorted order, see perlfaq4: \"How do I sort\na hash (optionally by value instead of key)?\".\n\nHow do I efficiently match many regular expressions at once?\n(contributed by brian d foy)\n\nYou want to avoid compiling a regular expression every time you want to\nmatch it. In this example, perl must recompile the regular expression\nfor every iteration of the \"foreach\" loop since $pattern can change:\n\nmy @patterns = qw( fo+ ba[rz] );\n\nLINE: while( my $line = <> ) {\nforeach my $pattern ( @patterns ) {\nif( $line =~ m/\\b$pattern\\b/i ) {\nprint $line;\nnext LINE;\n}\n}\n}\n\nThe \"qr//\" operator compiles a regular expression, but doesn't apply it.\nWhen you use the pre-compiled version of the regex, perl does less work.\nIn this example, I inserted a \"map\" to turn each pattern into its\npre-compiled form. The rest of the script is the same, but faster:\n\nmy @patterns = map { qr/\\b$\\b/i } qw( fo+ ba[rz] );\n\nLINE: while( my $line = <> ) {\nforeach my $pattern ( @patterns ) {\nif( $line =~ m/$pattern/ ) {\nprint $line;\nnext LINE;\n}\n}\n}\n\nIn some cases, you may be able to make several patterns into a single\nregular expression. Beware of situations that require backtracking\nthough. In this example, the regex is only compiled once because $regex\ndoesn't change between iterations:\n\nmy $regex = join '|', qw( fo+ ba[rz] );\n\nwhile( my $line = <> ) {\nprint if $line =~ m/\\b(?:$regex)\\b/i;\n}\n\nThe function \"list2re\" in Data::Munge on CPAN can also be used to form a\nsingle regex that matches a list of literal strings (not regexes).\n\nFor more details on regular expression efficiency, see *Mastering\nRegular Expressions* by Jeffrey Friedl. He explains how the regular\nexpressions engine works and why some patterns are surprisingly\ninefficient. Once you understand how perl applies regular expressions,\nyou can tune them for individual situations.\n\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": "Can I get a BNF/yacc/RE for the Perl language?\nThere is no BNF, but you can paw your way through the yacc grammar in\nperly.y in the source distribution if you're particularly brave. The\ngrammar relies on very smart tokenizing code, so be prepared to venture\ninto toke.c as well.\n\nIn the words of Chaim Frenkel: \"Perl's grammar can not be reduced to\nBNF. The work of parsing perl is distributed between yacc, the lexer,\nsmoke and mirrors.\"\n\nWhat are all these $@%&* punctuation signs, and how do I know when to use them?\nThey are type specifiers, as detailed in perldata:\n\n$ for scalar values (number, string or reference)\n@ for arrays\n% for hashes (associative arrays)\n& for subroutines (aka functions, procedures, methods)\n* for all types of that symbol name. In version 4 you used them like\npointers, but in modern perls you can just use references.\n\nThere are a couple of other symbols that you're likely to encounter that\naren't really type specifiers:\n\n<> are used for inputting a record from a filehandle.\n\\  takes a reference to something.\n\nNote that <FILE> is *neither* the type specifier for files nor the name\nof the handle. It is the \"<>\" operator applied to the handle FILE. It\nreads one line (well, record--see \"$/\" in perlvar) from the handle FILE\nin scalar context, or *all* lines in list context. When performing open,\nclose, or any other operation besides \"<>\" on files, or even when\ntalking about the handle, do *not* use the brackets. These are correct:\n\"eof(FH)\", \"seek(FH, 0, 2)\" and \"copying from STDIN to FILE\".\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\nWhy do Perl operators have different precedence than C operators?\nActually, they don't. All C operators that Perl copies have the same\nprecedence in Perl as they do in C. The problem is with operators that C\ndoesn't have, especially functions that give a list context to\neverything on their right, eg. print, chmod, exec, and so on. Such\nfunctions are called \"list operators\" and appear as such in the\nprecedence table in perlop.\n\nA common mistake is to write:\n\nunlink $file || die \"snafu\";\n\nThis gets interpreted as:\n\nunlink ($file || die \"snafu\");\n\nTo avoid this problem, either put in extra parentheses or use the super\nlow precedence \"or\" operator:\n\n(unlink $file) || die \"snafu\";\nunlink $file or die \"snafu\";\n\nThe \"English\" operators (\"and\", \"or\", \"xor\", and \"not\") deliberately\nhave precedence lower than that of list operators for just such\nsituations as the one above.\n\nAnother operator with surprising precedence is exponentiation. It binds\nmore tightly even than unary minus, making \"-22\" produce a negative\nfour and not a positive one. It is also right-associating, meaning that\n\"232\" is two raised to the ninth power, not eight squared.\n\nAlthough it has the same precedence as in C, Perl's \"?:\" operator\nproduces an lvalue. This assigns $x to either $iftrue or $iffalse,\ndepending on the trueness of $maybe:\n\n($maybe ? $iftrue : $iffalse) = $x;\n\nHow 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\nWhat's a closure?\nClosures are documented in perlref.\n\n*Closure* is a computer science term with a precise but hard-to-explain\nmeaning. Usually, closures are implemented in Perl as anonymous\nsubroutines with lasting references to lexical variables outside their\nown scopes. These lexicals magically refer to the variables that were\naround when the subroutine was defined (deep binding).\n\nClosures are most often used in programming languages where you can have\nthe return value of a function be itself a function, as you can in Perl.\nNote that some languages provide anonymous functions but are not capable\nof providing proper closures: the Python language, for example. For more\ninformation on closures, check out any textbook on functional\nprogramming. Scheme is a language that not only supports but encourages\nclosures.\n\nHere's a classic non-closure function-generating function:\n\nsub addfunctiongenerator {\nreturn sub { shift() + shift() };\n}\n\nmy $addsub = addfunctiongenerator();\nmy $sum = $addsub->(4,5);                # $sum is 9 now.\n\nThe anonymous subroutine returned by addfunctiongenerator() isn't\ntechnically a closure because it refers to no lexicals outside its own\nscope. Using a closure gives you a *function template* with some\ncustomization slots left out to be filled later.\n\nContrast this with the following makeadder() function, in which the\nreturned anonymous function contains a reference to a lexical variable\noutside the scope of that function itself. Such a reference requires\nthat Perl return a proper closure, thus locking in for all time the\nvalue that the lexical had when the function was created.\n\nsub makeadder {\nmy $addpiece = shift;\nreturn sub { shift() + $addpiece };\n}\n\nmy $f1 = makeadder(20);\nmy $f2 = makeadder(555);\n\nNow \"$f1->($n)\" is always 20 plus whatever $n you pass in, whereas\n\"$f2->($n)\" is always 555 plus whatever $n you pass in. The $addpiece in\nthe closure sticks around.\n\nClosures are often used for less esoteric purposes. For example, when\nyou want to pass in a bit of code into a function:\n\nmy $line;\ntimeout( 30, sub { $line = <STDIN> } );\n\nIf the code to execute had been passed in as a string, '$line =\n<STDIN>', there would have been no way for the hypothetical timeout()\nfunction to access the lexical variable $line back in its caller's\nscope.\n\nAnother use for a closure is to make a variable *private* to a named\nsubroutine, e.g. a counter that gets initialized at creation time of the\nsub and can only be modified from within the sub. This is sometimes used\nwith a BEGIN block in package files to make sure a variable doesn't get\nmeddled with during the lifetime of the package:\n\nBEGIN {\nmy $id = 0;\nsub nextid { ++$id }\n}\n\nThis is discussed in more detail in perlsub; see the entry on\n*Persistent Private Variables*.\n\nWhat is variable suicide and how can I prevent it?\nThis problem was fixed in perl 5.00405, so preventing it means\nupgrading your version of perl. ;)\n\nVariable suicide is when you (temporarily or permanently) lose the value\nof a variable. It is caused by scoping through my() and local()\ninteracting with either closures or aliased foreach() iterator variables\nand subroutine arguments. It used to be easy to inadvertently lose a\nvariable's value this way, but now it's much harder. Take this code:\n\nmy $f = 'foo';\nsub T {\nwhile ($i++ < 3) { my $f = $f; $f .= \"bar\"; print $f, \"\\n\" }\n}\n\nT;\nprint \"Finally $f\\n\";\n\nIf you are experiencing variable suicide, that \"my $f\" in the subroutine\ndoesn't pick up a fresh copy of the $f whose value is 'foo'. The output\nshows that inside the subroutine the value of $f leaks through when it\nshouldn't, as in this output:\n\nfoobar\nfoobarbar\nfoobarbarbar\nFinally foo\n\nThe $f that has \"bar\" added to it three times should be a new $f \"my $f\"\nshould create a new lexical variable each time through the loop. The\nexpected output is:\n\nfoobar\nfoobar\nfoobar\nFinally foo\n\nHow can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?\nYou need to pass references to these objects. See \"Pass by Reference\" in\nperlsub for this particular question, and perlref for information on\nreferences.\n\nPassing Variables and Functions\nRegular variables and functions are quite easy to pass: just pass in\na reference to an existing or anonymous variable or function:\n\nfunc( \\$somescalar );\n\nfunc( \\@somearray  );\nfunc( [ 1 .. 10 ]   );\n\nfunc( \\%somehash   );\nfunc( { this => 10, that => 20 }   );\n\nfunc( \\&somefunc   );\nfunc( sub { $[0]  $[1] }   );\n\nPassing Filehandles\nAs of Perl 5.6, you can represent filehandles with scalar variables\nwhich you treat as any other scalar.\n\nopen my $fh, $filename or die \"Cannot open $filename! $!\";\nfunc( $fh );\n\nsub func {\nmy $passedfh = shift;\n\nmy $line = <$passedfh>;\n}\n\nBefore Perl 5.6, you had to use the *FH or \"\\*FH\" notations. These\nare \"typeglobs\"--see \"Typeglobs and Filehandles\" in perldata and\nespecially \"Pass by Reference\" in perlsub for more information.\n\nPassing Regexes\nHere's an example of how to pass in a string and a regular\nexpression for it to match against. You construct the pattern with\nthe \"qr//\" operator:\n\nsub compare {\nmy ($val1, $regex) = @;\nmy $retval = $val1 =~ /$regex/;\nreturn $retval;\n}\n$match = compare(\"old McDonald\", qr/d.*D/i);\n\nPassing Methods\nTo pass an object method into a subroutine, you can do this:\n\ncallalot(10, $someobj, \"methname\")\nsub callalot {\nmy ($count, $widget, $trick) = @;\nfor (my $i = 0; $i < $count; $i++) {\n$widget->$trick();\n}\n}\n\nOr, you can use a closure to bundle up the object, its method call,\nand arguments:\n\nmy $whatnot = sub { $someobj->obfuscate(@args) };\nfunc($whatnot);\nsub func {\nmy $code = shift;\n&$code();\n}\n\nYou could also investigate the can() method in the UNIVERSAL class\n(part of the standard perl distribution).\n\nHow do I create a static variable?\n(contributed by brian d foy)\n\nIn Perl 5.10, declare the variable with \"state\". The \"state\" declaration\ncreates the lexical variable that persists between calls to the\nsubroutine:\n\nsub counter { state $count = 1; $count++ }\n\nYou can fake a static variable by using a lexical variable which goes\nout of scope. In this example, you define the subroutine \"counter\", and\nit uses the lexical variable $count. Since you wrap this in a BEGIN\nblock, $count is defined at compile-time, but also goes out of scope at\nthe end of the BEGIN block. The BEGIN block also ensures that the\nsubroutine and the value it uses is defined at compile-time so the\nsubroutine is ready to use just like any other subroutine, and you can\nput this code in the same place as other subroutines in the program text\n(i.e. at the end of the code, typically). The subroutine \"counter\" still\nhas a reference to the data, and is the only way you can access the\nvalue (and each time you do, you increment the value). The data in chunk\nof memory defined by $count is private to \"counter\".\n\nBEGIN {\nmy $count = 1;\nsub counter { $count++ }\n}\n\nmy $start = counter();\n\n.... # code that calls counter();\n\nmy $end = counter();\n\nIn the previous example, you created a function-private variable because\nonly one function remembered its reference. You could define multiple\nfunctions while the variable is in scope, and each function can share\nthe \"private\" variable. It's not really \"static\" because you can access\nit outside the function while the lexical variable is in scope, and even\ncreate references to it. In this example, \"incrementcount\" and\n\"returncount\" share the variable. One function adds to the value and\nthe other simply returns the value. They can both access $count, and\nsince it has gone out of scope, there is no other way to access it.\n\nBEGIN {\nmy $count = 1;\nsub incrementcount { $count++ }\nsub returncount    { $count }\n}\n\nTo declare a file-private variable, you still use a lexical variable. A\nfile is also a scope, so a lexical variable defined in the file cannot\nbe seen from any other file.\n\nSee \"Persistent Private Variables\" in perlsub for more information. The\ndiscussion of closures in perlref may help you even though we did not\nuse anonymous subroutines in this answer. See \"Persistent Private\nVariables\" in perlsub for details.\n\nWhat's the difference between dynamic and lexical (static) scoping? Between local() and my()?\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",
                "subsections": [
                    {
                        "name": "local",
                        "content": "What's the difference between deep and shallow binding?\nIn deep binding, lexical variables mentioned in anonymous subroutines\nare the same ones that were in scope when the subroutine was created. In\nshallow binding, they are whichever variables with the same names happen\nto be in scope when the subroutine is called. Perl always uses deep\nbinding of lexical variables (i.e., those created with my()). However,\ndynamic variables (aka global, local, or package variables) are\neffectively shallowly bound. Consider this just one more reason not to\nuse them. See the answer to \"What's a closure?\".\n\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 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\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 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 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 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 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\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\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\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 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\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",
                "subsections": []
            },
            "Found in /usr/share/perl/5.34/pod/perlfaq9.pod": {
                "content": "How 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 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 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 check a valid mail address?\n(partly contributed by Aaron Sherman)\n\nThis isn't as simple a question as it sounds. There are two parts:\n\na) How do I verify that an email address is correctly formatted?\n\nb) How do I verify that an email address targets a valid recipient?\n\nWithout sending mail to the address and seeing whether there's a human\non the other end to answer you, you cannot fully answer part *b*, but\nthe Email::Valid module will do both part *a* and part *b* as far as you\ncan in real-time.\n\nOur best advice for verifying a person's mail address is to have them\nenter their address twice, just as you normally do to change a password.\nThis usually weeds out typos. If both versions match, send mail to that\naddress with a personal message. If you get the message back and they've\nfollowed your directions, you can be reasonably assured that it's real.\n\nA related strategy that's less open to forgery is to give them a PIN\n(personal ID number). Record the address and PIN (best that it be a\nrandom one) for later processing. In the mail you send, include a link\nto your site with the PIN included. If the mail bounces, you know it's\nnot valid. If they don't click on the link, either they forged the\naddress or (assuming they got the message) following through wasn't\nimportant so you don't need to worry about it.\n\nHow do I find the user's mail address?\nAsk them for it. There are so many email providers available that it's\nunlikely the local system has any idea how to determine a user's email\naddress.\n\nThe exception is for organization-specific email (e.g.\nfoo@yourcompany.com) where policy can be codified in your program. In\nthat case, you could look at $ENV{USER}, $ENV{LOGNAME}, and getpwuid($<)\nin scalar context, like so:\n\nmy $username = getpwuid($<)\n\nBut you still cannot make assumptions about whether this is correct,\nunless your policy says it is. You really are best off asking the user.\n\nHow do I 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",
                "subsections": []
            }
        }
    }
}