{
    "mode": "perldoc",
    "parameter": "It",
    "section": "-q",
    "url": "https://www.chedong.com/phpMan.php/perldoc/It/json",
    "generated": "2026-11-02T04:13:43Z",
    "sections": {
        "Found in /usr/share/perl/5.38/pod/perlfaq1.pod": {
            "content": "Who supports Perl? Who develops it? Why is it free?\nThe original culture of the pre-populist Internet and the deeply-held\nbeliefs of Perl's author, Larry Wall, gave rise to the free and open\ndistribution policy of Perl. Perl is supported by its users. The core,\nthe standard Perl library, the optional modules, and the documentation\nyou're reading now were all written by volunteers.\n\nThe core development team (known as the Perl Porters) are a group of\nhighly altruistic individuals committed to producing better software for\nfree than you could hope to purchase for money. You may snoop on pending\ndevelopments via the archives\n<http://www.nntp.perl.org/group/perl.perl5.porters/> or you can\nsubscribe to the mailing list by sending\nperl5-porters-subscribe@perl.org a subscription request (an empty\nmessage with no subject is fine).\n\nWhile the GNU project includes Perl in its distributions, there's no\nsuch thing as \"GNU Perl\". Perl is not produced nor maintained by the\nFree Software Foundation. Perl's licensing terms are also more open than\nGNU software's tend to be.\n\nYou can get commercial support of Perl if you wish, although for most\nusers the informal support will more than suffice. See the answer to\n\"Where can I buy a commercial version of Perl?\" for more information.\n\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",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq2.pod": {
            "content": "What machines support Perl? Where do I get it?\nThe standard release of Perl (the one maintained by the Perl development\nteam) is distributed only in source code form. You can find the latest\nreleases at <http://www.cpan.org/src/>.\n\nPerl builds and runs on a bewildering number of platforms. Virtually all\nknown and current Unix derivatives are supported (perl's native\nplatform), as are other systems like VMS, DOS, OS/2, Windows, QNX, BeOS,\nOS X, MPE/iX and the Amiga.\n\nBinary distributions for some proprietary platforms can be found\n<http://www.cpan.org/ports/> directory. Because these are not part of\nthe standard distribution, they may and in fact do differ from the base\nperl port in a variety of ways. You'll have to check their respective\nrelease notes to see just what the differences are. These differences\ncan be either positive (e.g. extensions for the features of the\nparticular platform that are not supported in the source release of\nperl) or negative (e.g. might be based upon a less current source\nrelease of perl).\n\nI grabbed the sources and tried to compile but gdbm/dynamic loading/malloc/linking/... failed. How do I make it work?\nRead the INSTALL file, which is part of the source distribution. It\ndescribes in detail how to cope with most idiosyncrasies that the\n\"Configure\" script can't work around for any given system or\narchitecture.\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq3.pod": {
            "content": "Is 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\nHow can I use curses with Perl?\nThe Curses module from CPAN provides a dynamically loadable object\nmodule interface to a curses library. A small demo can be found at the\ndirectory <http://www.cpan.org/authors/id/T/TO/TOMC/scripts/rep.gz> ;\nthis program repeats a command and updates the screen as needed,\nrendering rep ps axu similar to top.\n\nHow can I write a GUI (X, Tk, Gtk, etc.) in Perl?\n(contributed by Ben Morrow)\n\nThere are a number of modules which let you write GUIs in Perl. Most GUI\ntoolkits have a perl interface: an incomplete list follows.\n\nTk  This works under Unix and Windows, and the current version doesn't\nlook half as bad under Windows as it used to. Some of the gui\nelements still don't 'feel' quite right, though. The interface is\nvery natural and 'perlish', making it easy to use in small scripts\nthat just need a simple gui. It hasn't been updated in a while.\n\nWx  This is a Perl binding for the cross-platform wxWidgets toolkit (\n<http://www.wxwidgets.org> ). It works under Unix, Win32 and Mac OS\nX, using native widgets (Gtk under Unix). The interface follows the\nC++ interface closely, but the documentation is a little sparse for\nsomeone who doesn't know the library, mostly just referring you to\nthe C++ documentation.\n\nGtk and Gtk2\nThese are Perl bindings for the Gtk toolkit ( <http://www.gtk.org>\n). The interface changed significantly between versions 1 and 2 so\nthey have separate Perl modules. It runs under Unix, Win32 and Mac\nOS X (currently it requires an X server on Mac OS, but a 'native'\nport is underway), and the widgets look the same on every platform:\ni.e., they don't match the native widgets. As with Wx, the Perl\nbindings follow the C API closely, and the documentation requires\nyou to read the C documentation to understand it.\n\nWin32::GUI\nThis provides access to most of the Win32 GUI widgets from Perl.\nObviously, it only runs under Win32, and uses native widgets. The\nPerl interface doesn't really follow the C interface: it's been made\nmore Perlish, and the documentation is pretty good. More advanced\nstuff may require familiarity with the C Win32 APIs, or reference to\nMSDN.\n\nCamelBones\nCamelBones ( <http://camelbones.sourceforge.net> ) is a Perl\ninterface to Mac OS X's Cocoa GUI toolkit, and as such can be used\nto produce native GUIs on Mac OS X. It's not on CPAN, as it requires\nframeworks that CPAN.pm doesn't know how to install, but\ninstallation is via the standard OSX package installer. The Perl API\nis, again, very close to the ObjC API it's wrapping, and the\ndocumentation just tells you how to translate from one to the other.\n\nQt  There is a Perl interface to TrollTech's Qt toolkit, but it does not\nappear to be maintained.\n\nAthena\nSx is an interface to the Athena widget set which comes with X, but\nagain it appears not to be much used nowadays.\n\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\nCan I write useful Perl programs on the command line?\nYes. Read perlrun for more information. Some examples follow. (These\nassume standard Unix shell quoting rules.)\n\n# sum first and last fields\nperl -lane 'print $F[0] + $F[-1]' *\n\n# identify text files\nperl -le 'for(@ARGV) {print if -f && -T }' *\n\n# remove (most) comments from C program\nperl -0777 -pe 's{/\\*.*?\\*/}{}gs' foo.c\n\n# make file a month younger than today, defeating reaper daemons\nperl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *\n\n# find first unused uid\nperl -le '$i++ while getpwuid($i); print $i'\n\n# display reasonable manpath\necho $PATH | perl -nl -072 -e '\ns![^/+]*$!man!&&-d&&!$s{$}++&&push@m,$;END{print\"@m\"}'\n\nOK, the last one was actually an Obfuscated Perl Contest entry. :-)\n\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\nWhen I tried to run my script, I got this message. What does it mean?\nA complete list of Perl's error messages and warnings with explanatory\ntext can be found in perldiag. You can also use the splain program\n(distributed with Perl) to explain the error messages:\n\nperl program 2>diag.out\nsplain [-v] [-p] diag.out\n\nor change your program to explain the messages for you:\n\nuse diagnostics;\n\nor\n\nuse diagnostics -verbose;\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq4.pod": {
            "content": "Why doesn't & work the way I want it to?\nThe behavior of binary arithmetic operators depends on whether they're\nused on numbers or strings. The operators treat a string as a series of\nbits and work with that (the string \"3\" is the bit pattern 00110011).\nThe operators work with the binary form of a number (the number 3 is\ntreated as the bit pattern 00000011).\n\nSo, saying \"11 & 3\" performs the \"and\" operation on numbers (yielding\n3). Saying \"11\" & \"3\" performs the \"and\" operation on strings (yielding\n\"1\").\n\nMost problems with \"&\" and \"|\" arise because the programmer thinks they\nhave a number but really it's a string or vice versa. To avoid this,\nstringify the arguments explicitly (using \"\" or qq()) or convert them to\nnumbers explicitly (using \"0+$arg\"). The rest arise because the\nprogrammer says:\n\nif (\"\\020\\020\" & \"\\101\\101\") {\n# ...\n}\n\nbut a string consisting of two null bytes (the result of \"\\020\\020\" &\n\"\\101\\101\") is not a false value in Perl. You need:\n\nif ( (\"\\020\\020\" & \"\\101\\101\") !~ /[^\\000]/) {\n# ...\n}\n\nHow can I take a string and turn it into epoch seconds?\nIf it's a regular enough string that it always has the same format, you\ncan split it up and pass the parts to \"timelocal\" in the standard\nTime::Local module. Otherwise, you should look into the Date::Calc,\nDate::Parse, and Date::Manip modules from CPAN.\n\nHow can I count the number of occurrences of a substring within a string?\nThere are a number of ways, with varying efficiency. If you want a count\nof a certain single character (X) within a string, you can use the\n\"tr///\" function like so:\n\nmy $string = \"ThisXlineXhasXsomeXx'sXinXit\";\nmy $count = ($string =~ tr/X//);\nprint \"There are $count X characters in the string\";\n\nThis is fine if you are just looking for a single character. However, if\nyou are trying to count multiple character substrings within a larger\nstring, \"tr///\" won't work. What you can do is wrap a while() loop\naround a global pattern match. For example, let's count negative\nintegers:\n\nmy $string = \"-9 55 48 -2 23 -76 4 14 -44\";\nmy $count = 0;\nwhile ($string =~ /-\\d+/g) { $count++ }\nprint \"There are $count negative numbers in the string\";\n\nAnother version uses a global match in list context, then assigns the\nresult to a scalar, producing a count of the number of matches.\n\nmy $count = () = $string =~ /-\\d+/g;\n\nHow do I capitalize all the words on one line?\n(contributed by brian d foy)\n\nDamian Conway's Text::Autoformat handles all of the thinking for you.\n\nuse Text::Autoformat;\nmy $x = \"Dr. Strangelove or: How I Learned to Stop \".\n\"Worrying and Love the Bomb\";\n\nprint $x, \"\\n\";\nfor my $style (qw( sentence title highlight )) {\nprint autoformat($x, { case => $style }), \"\\n\";\n}\n\nHow do you want to capitalize those words?\n\nFRED AND BARNEY'S LODGE        # all uppercase\nFred And Barney's Lodge        # title case\nFred and Barney's Lodge        # highlight case\n\nIt's not as easy a problem as it looks. How many words do you think are\nin there? Wait for it... wait for it.... If you answered 5 you're right.\nPerl words are groups of \"\\w+\", but that's not what you want to\ncapitalize. How is Perl supposed to know not to capitalize that \"s\"\nafter the apostrophe? You could try a regular expression:\n\n$string =~ s/ (\n(^\\w)    #at the beginning of the line\n|      # or\n(\\s\\w)   #preceded by whitespace\n)\n/\\U$1/xg;\n\n$string =~ s/([\\w']+)/\\u\\L$1/g;\n\nNow, what if you don't want to capitalize that \"and\"? Just use\nText::Autoformat and get on with the next problem. :)\n\nHow can I split a [character]-delimited string except when inside [character]?\nSeveral modules can handle this sort of parsing--Text::Balanced,\nText::CSV, Text::CSVXS, and Text::ParseWords, among others.\n\nTake the example case of trying to split a string that is\ncomma-separated into its different fields. You can't use \"split(/,/)\"\nbecause you shouldn't split if the comma is inside quotes. For example,\ntake a data line like this:\n\nSAR001,\"\",\"Cimetrix, Inc\",\"Bob Smith\",\"CAM\",N,8,1,0,7,\"Error, Core Dumped\"\n\nDue to the restriction of the quotes, this is a fairly complex problem.\nThankfully, we have Jeffrey Friedl, author of *Mastering Regular\nExpressions*, to handle these for us. He suggests (assuming your string\nis contained in $text):\n\nmy @new = ();\npush(@new, $+) while $text =~ m{\n\"([^\\\"\\\\]*(?:\\\\.[^\\\"\\\\]*)*)\",? # groups the phrase inside the quotes\n| ([^,]+),?\n| ,\n}gx;\npush(@new, undef) if substr($text,-1,1) eq ',';\n\nIf you want to represent quotation marks inside a\nquotation-mark-delimited field, escape them with backslashes (eg, \"like\n\\\"this\\\"\".\n\nAlternatively, the Text::ParseWords module (part of the standard Perl\ndistribution) lets you say:\n\nuse Text::ParseWords;\n@new = quotewords(\",\", 0, $text);\n\nFor parsing or generating CSV, though, using Text::CSV rather than\nimplementing it yourself is highly recommended; you'll save yourself odd\nbugs popping up later by just using code which has already been tried\nand tested in production for years.\n\nHow do I pad a string with blanks or pad a number with zeroes?\nIn the following examples, $padlen is the length to which you wish to\npad the string, $text or $num contains the string to be padded, and\n$padchar contains the padding character. You can use a single character\nstring constant instead of the $padchar variable if you know what it is\nin advance. And in the same way you can use an integer in place of\n$padlen if you know the pad length in advance.\n\nThe simplest method uses the \"sprintf\" function. It can pad on the left\nor right with blanks and on the left with zeroes and it will not\ntruncate the result. The \"pack\" function can only pad strings on the\nright with blanks and it will truncate the result to a maximum length of\n$padlen.\n\n# Left padding a string with blanks (no truncation):\nmy $padded = sprintf(\"%${padlen}s\", $text);\nmy $padded = sprintf(\"%*s\", $padlen, $text);  # same thing\n\n# Right padding a string with blanks (no truncation):\nmy $padded = sprintf(\"%-${padlen}s\", $text);\nmy $padded = sprintf(\"%-*s\", $padlen, $text); # same thing\n\n# Left padding a number with 0 (no truncation):\nmy $padded = sprintf(\"%0${padlen}d\", $num);\nmy $padded = sprintf(\"%0*d\", $padlen, $num); # same thing\n\n# Right padding a string with blanks using pack (will truncate):\nmy $padded = pack(\"A$padlen\",$text);\n\nIf you need to pad with a character other than blank or zero you can use\none of the following methods. They all generate a pad string with the\n\"x\" operator and combine that with $text. These methods do not truncate\n$text.\n\nLeft and right padding with any character, creating a new string:\n\nmy $padded = $padchar x ( $padlen - length( $text ) ) . $text;\nmy $padded = $text . $padchar x ( $padlen - length( $text ) );\n\nLeft and right padding with any character, modifying $text directly:\n\nsubstr( $text, 0, 0 ) = $padchar x ( $padlen - length( $text ) );\n$text .= $padchar x ( $padlen - length( $text ) );\n\nWhat's wrong with always quoting \"$vars\"?\nThe problem is that those double-quotes force stringification--coercing\nnumbers and references into strings--even when you don't want them to be\nstrings. Think of it this way: double-quote expansion is used to produce\nnew strings. If you already have a string, why do you need more?\n\nIf you get used to writing odd things like these:\n\nprint \"$var\";       # BAD\nmy $new = \"$old\";       # BAD\nsomefunc(\"$var\");    # BAD\n\nYou'll be in trouble. Those should (in 99.8% of the cases) be the\nsimpler and more direct:\n\nprint $var;\nmy $new = $old;\nsomefunc($var);\n\nOtherwise, besides slowing you down, you're going to break code when the\nthing in the scalar is actually neither a string nor a number, but a\nreference:\n\nfunc(\\@array);\nsub func {\nmy $aref = shift;\nmy $oref = \"$aref\";  # WRONG\n}\n\nYou can also get into subtle problems on those few operations in Perl\nthat actually do care about the difference between a string and a\nnumber, such as the magical \"++\" autoincrement operator or the syscall()\nfunction.\n\nStringification also destroys arrays.\n\nmy @lines = `command`;\nprint \"@lines\";     # WRONG - extra blanks\nprint @lines;       # right\n\nHow do I find the first array element for which a condition is true?\nTo find the first array element which satisfies a condition, you can use\nthe first() function in the List::Util module, which comes with Perl\n5.8. This example finds the first element that contains \"Perl\".\n\nuse List::Util qw(first);\n\nmy $element = first { /Perl/ } @array;\n\nIf you cannot use List::Util, you can make your own loop to do the same\nthing. Once you find the element, you stop the loop with last.\n\nmy $found;\nforeach ( @array ) {\nif( /Perl/ ) { $found = $; last }\n}\n\nIf you want the array index, use the firstidx() function from\n\"List::MoreUtils\":\n\nuse List::MoreUtils qw(firstidx);\nmy $index = firstidx { /Perl/ } @array;\n\nOr write it yourself, iterating through the indices and checking the\narray element at each index until you find one that satisfies the\ncondition:\n\nmy( $found, $index ) = ( undef, -1 );\nfor( $i = 0; $i < @array; $i++ ) {\nif( $array[$i] =~ /Perl/ ) {\n$found = $array[$i];\n$index = $i;\nlast;\n}\n}\n\nHow do I manipulate arrays of bits?\nUse pack() and unpack(), or else vec() and the bitwise operations.\n\nFor example, you don't have to store individual bits in an array (which\nwould mean that you're wasting a lot of space). To convert an array of\nbits to a string, use vec() to set the right bits. This sets $vec to\nhave bit N set only if $ints[N] was set:\n\nmy @ints = (...); # array of bits, e.g. ( 1, 0, 0, 1, 1, 0 ... )\nmy $vec = '';\nforeach( 0 .. $#ints ) {\nvec($vec,$,1) = 1 if $ints[$];\n}\n\nThe string $vec only takes up as many bits as it needs. For instance, if\nyou had 16 entries in @ints, $vec only needs two bytes to store them\n(not counting the scalar variable overhead).\n\nHere's how, given a vector in $vec, you can get those bits into your\n@ints array:\n\nsub bitvectolist {\nmy $vec = shift;\nmy @ints;\n# Find null-byte density then select best algorithm\nif ($vec =~ tr/\\0// / length $vec > 0.95) {\nuse integer;\nmy $i;\n\n# This method is faster with mostly null-bytes\nwhile($vec =~ /[^\\0]/g ) {\n$i = -9 + 8 * pos $vec;\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\n}\n}\nelse {\n# This method is a fast general algorithm\nuse integer;\nmy $bits = unpack \"b*\", $vec;\npush @ints, 0 if $bits =~ s/^(\\d)// && $1;\npush @ints, pos $bits while($bits =~ /1/g);\n}\n\nreturn \\@ints;\n}\n\nThis method gets faster the more sparse the bit vector is. (Courtesy of\nTim Bunce and Winfried Koenig.)\n\nYou can make the while loop a lot shorter with this suggestion from\nBenjamin Goldberg:\n\nwhile($vec =~ /[^\\0]+/g ) {\npush @ints, grep vec($vec, $, 1), $-[0] * 8 .. $+[0] * 8;\n}\n\nOr use the CPAN module Bit::Vector:\n\nmy $vector = Bit::Vector->new($numofbits);\n$vector->IndexListStore(@ints);\nmy @ints = $vector->IndexListRead();\n\nBit::Vector provides efficient methods for bit vector, sets of small\nintegers and \"big int\" math.\n\nHere's a more extensive illustration using vec():\n\n# vec demo\nmy $vector = \"\\xff\\x0f\\xef\\xfe\";\nprint \"Ilya's string \\\\xff\\\\x0f\\\\xef\\\\xfe represents the number \",\nunpack(\"N\", $vector), \"\\n\";\nmy $isset = vec($vector, 23, 1);\nprint \"Its 23rd bit is \", $isset ? \"set\" : \"clear\", \".\\n\";\npvec($vector);\n\nsetvec(1,1,1);\nsetvec(3,1,1);\nsetvec(23,1,1);\n\nsetvec(3,1,3);\nsetvec(3,2,3);\nsetvec(3,4,3);\nsetvec(3,4,7);\nsetvec(3,8,3);\nsetvec(3,8,7);\n\nsetvec(0,32,17);\nsetvec(1,32,17);\n\nsub setvec {\nmy ($offset, $width, $value) = @;\nmy $vector = '';\nvec($vector, $offset, $width) = $value;\nprint \"offset=$offset width=$width value=$value\\n\";\npvec($vector);\n}\n\nsub pvec {\nmy $vector = shift;\nmy $bits = unpack(\"b*\", $vector);\nmy $i = 0;\nmy $BASE = 8;\n\nprint \"vector length in bytes: \", length($vector), \"\\n\";\n@bytes = unpack(\"A8\" x length($vector), $bits);\nprint \"bits are: @bytes\\n\\n\";\n}\n\nWhat happens if I add or remove keys from a hash while iterating over it?\n(contributed by brian d foy)\n\nThe easy answer is \"Don't do that!\"\n\nIf you iterate through the hash with each(), you can delete the key most\nrecently returned without worrying about it. If you delete or add other\nkeys, the iterator may skip or double up on them since perl may\nrearrange the hash table. See the entry for each() in perlfunc.\n\nWhat's the difference between \"delete\" and \"undef\" with hashes?\nHashes contain pairs of scalars: the first is the key, the second is the\nvalue. The key will be coerced to a string, although the value can be\nany kind of scalar: string, number, or reference. If a key $key is\npresent in %hash, exists($hash{$key}) will return true. The value for a\ngiven key can be \"undef\", in which case $hash{$key} will be \"undef\"\nwhile \"exists $hash{$key}\" will return true. This corresponds to ($key,\n\"undef\") being in the hash.\n\nPictures help... Here's the %hash table:\n\nkeys  values\n+------+------+\n|  a   |  3   |\n|  x   |  7   |\n|  d   |  0   |\n|  e   |  2   |\n+------+------+\n\nAnd these conditions hold\n\n$hash{'a'}                       is true\n$hash{'d'}                       is false\ndefined $hash{'d'}               is true\ndefined $hash{'a'}               is true\nexists $hash{'a'}                is true (Perl 5 only)\ngrep ($ eq 'a', keys %hash)     is true\n\nIf you now say\n\nundef $hash{'a'}\n\nyour table now reads:\n\nkeys  values\n+------+------+\n|  a   | undef|\n|  x   |  7   |\n|  d   |  0   |\n|  e   |  2   |\n+------+------+\n\nand these conditions now hold; changes in caps:\n\n$hash{'a'}                       is FALSE\n$hash{'d'}                       is false\ndefined $hash{'d'}               is true\ndefined $hash{'a'}               is FALSE\nexists $hash{'a'}                is true (Perl 5 only)\ngrep ($ eq 'a', keys %hash)     is true\n\nNotice the last two: you have an undef value, but a defined key!\n\nNow, consider this:\n\ndelete $hash{'a'}\n\nyour table now reads:\n\nkeys  values\n+------+------+\n|  x   |  7   |\n|  d   |  0   |\n|  e   |  2   |\n+------+------+\n\nand these conditions now hold; changes in caps:\n\n$hash{'a'}                       is false\n$hash{'d'}                       is false\ndefined $hash{'d'}               is true\ndefined $hash{'a'}               is false\nexists $hash{'a'}                is FALSE (Perl 5 only)\ngrep ($ eq 'a', keys %hash)     is FALSE\n\nSee, the whole entry is gone!\n\nHow can I make my hash remember the order I put elements into it?\nUse the Tie::IxHash from CPAN.\n\nuse Tie::IxHash;\n\ntie my %myhash, 'Tie::IxHash';\n\nfor (my $i=0; $i<20; $i++) {\n$myhash{$i} = 2*$i;\n}\n\nmy @keys = keys %myhash;\n# @keys = (0,1,2,3,...)\n\nWhy does passing a subroutine an undefined element in a hash create it?\n(contributed by brian d foy)\n\nAre you using a really old version of Perl?\n\nNormally, accessing a hash key's value for a nonexistent key will *not*\ncreate the key.\n\nmy %hash  = ();\nmy $value = $hash{ 'foo' };\nprint \"This won't print\\n\" if exists $hash{ 'foo' };\n\nPassing $hash{ 'foo' } to a subroutine used to be a special case,\nthough. Since you could assign directly to $[0], Perl had to be ready\nto make that assignment so it created the hash key ahead of time:\n\nmysub( $hash{ 'foo' } );\nprint \"This will print before 5.004\\n\" if exists $hash{ 'foo' };\n\nsub mysub {\n# $[0] = 'bar'; # create hash key in case you do this\n1;\n}\n\nSince Perl 5.004, however, this situation is a special case and Perl\ncreates the hash key only when you make the assignment:\n\nmysub( $hash{ 'foo' } );\nprint \"This will print, even after 5.004\\n\" if exists $hash{ 'foo' };\n\nsub mysub {\n$[0] = 'bar';\n}\n\nHowever, if you want the old behavior (and think carefully about that\nbecause it's a weird side effect), you can pass a hash slice instead.\nPerl 5.004 didn't make this a special case:\n\nmysub( @hash{ qw/foo/ } );\n\nHow can I prevent addition of unwanted keys into a hash?\nSince version 5.8.0, hashes can be *restricted* to a fixed number of\ngiven keys. Methods for creating and dealing with restricted hashes are\nexported by the Hash::Util module.\n\nHow do I verify a credit card checksum?\nGet the Business::CreditCard module from CPAN.\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq5.pod": {
            "content": "How can I use Perl's \"-i\" option from within a program?\n\"-i\" sets the value of Perl's $^I variable, which in turn affects the\nbehavior of \"<>\"; see perlrun for more details. By modifying the\nappropriate variables directly, you can get the same behavior within a\nlarger program. For example:\n\n# ...\n{\nlocal($^I, @ARGV) = ('.orig', glob(\"*.c\"));\nwhile (<>) {\nif ($. == 1) {\nprint \"This line should appear at the top of each file\\n\";\n}\ns/\\b(p)earl\\b/${1}erl/i;        # Correct typos, preserving case\nprint;\nclose ARGV if eof;              # Reset $.\n}\n}\n# $^I and @ARGV return to their old values here\n\nThis block modifies all the \".c\" files in the current directory, leaving\na backup of the original data from each file in a new \".c.orig\" file.\n\nHow can I set up a footer format to be used with write()?\nThere's no builtin way to do this, but perlform has a couple of\ntechniques to make it possible for the intrepid hacker.\n\nHow can I write() into a string?\n(contributed by brian d foy)\n\nIf you want to \"write\" into a string, you just have to <open> a\nfilehandle to a string, which Perl has been able to do since Perl 5.6:\n\nopen FH, '>', \\my $string;\nwrite( FH );\n\nSince you want to be a good programmer, you probably want to use a\nlexical filehandle, even though formats are designed to work with\nbareword filehandles since the default format names take the filehandle\nname. However, you can control this with some Perl special\nper-filehandle variables: $^, which names the top-of-page format, and $~\nwhich shows the line format. You have to change the default filehandle\nto set these variables:\n\nopen my($fh), '>', \\my $string;\n\n{ # set per-filehandle variables\nmy $oldfh = select( $fh );\n$~ = 'ANIMAL';\n$^ = 'ANIMALTOP';\nselect( $oldfh );\n}\n\nformat ANIMALTOP =\nID  Type    Name\n.\n\nformat ANIMAL =\n@##   @<<<    @<<<<<<<<<<<<<<\n$id,  $type,  $name\n.\n\nAlthough write can work with lexical or package variables, whatever\nvariables you use have to scope in the format. That most likely means\nyou'll want to localize some package variables:\n\n{\nlocal( $id, $type, $name ) = qw( 12 cat Buster );\nwrite( $fh );\n}\n\nprint $string;\n\nThere are also some tricks that you can play with \"formline\" and the\naccumulator variable $^A, but you lose a lot of the value of formats\nsince \"formline\" won't handle paging and so on. You end up\nreimplementing formats when you use them.\n\nHow can I output my numbers with commas added?\n(contributed by brian d foy and Benjamin Goldberg)\n\nYou can use Number::Format to separate places in a number. It handles\nlocale information for those of you who want to insert full stops\ninstead (or anything else that they want to use, really).\n\nThis subroutine will add commas to your number:\n\nsub commify {\nlocal $  = shift;\n1 while s/^([-+]?\\d+)(\\d{3})/$1,$2/;\nreturn $;\n}\n\nThis regex from Benjamin Goldberg will add commas to numbers:\n\ns/(^[-+]?\\d+?(?=(?>(?:\\d{3})+)(?!\\d))|\\G\\d{3}(?=\\d))/$1,/g;\n\nIt is easier to see with comments:\n\ns/(\n^[-+]?             # beginning of number.\n\\d+?               # first digits before first comma\n(?=                # followed by, (but not included in the match) :\n(?>(?:\\d{3})+) # some positive multiple of three digits.\n(?!\\d)         # an *exact* multiple, not x * 3 + 1 or whatever.\n)\n|                  # or:\n\\G\\d{3}            # after the last group, get three digits\n(?=\\d)             # but they have to have more digits after them.\n)/$1,/xg;\n\nHow come when I open a file read-write it wipes it out?\nBecause you're using something like this, which truncates the file\n*then* gives you read-write access:\n\nopen my $fh, '+>', '/path/name'; # WRONG (almost always)\n\nWhoops. You should instead use this, which will fail if the file doesn't\nexist:\n\nopen my $fh, '+<', '/path/name'; # open for update\n\nUsing \">\" always clobbers or creates. Using \"<\" never does either. The\n\"+\" doesn't change this.\n\nHere are examples of many kinds of file opens. Those using \"sysopen\" all\nassume that you've pulled in the constants from Fcntl:\n\nuse Fcntl;\n\nTo open file for reading:\n\nopen my $fh, '<', $path                               or die $!;\nsysopen my $fh, $path, ORDONLY                       or die $!;\n\nTo open file for writing, create new file if needed or else truncate old\nfile:\n\nopen my $fh, '>', $path                               or die $!;\nsysopen my $fh, $path, OWRONLY|OTRUNC|OCREAT       or die $!;\nsysopen my $fh, $path, OWRONLY|OTRUNC|OCREAT, 0666 or die $!;\n\nTo open file for writing, create new file, file must not exist:\n\nsysopen my $fh, $path, OWRONLY|OEXCL|OCREAT        or die $!;\nsysopen my $fh, $path, OWRONLY|OEXCL|OCREAT, 0666  or die $!;\n\nTo open file for appending, create if necessary:\n\nopen my $fh, '>>', $path                              or die $!;\nsysopen my $fh, $path, OWRONLY|OAPPEND|OCREAT      or die $!;\nsysopen my $fh, $path, OWRONLY|OAPPEND|OCREAT, 0666 or die $!;\n\nTo open file for appending, file must exist:\n\nsysopen my $fh, $path, OWRONLY|OAPPEND              or die $!;\n\nTo open file for update, file must exist:\n\nopen my $fh, '+<', $path                              or die $!;\nsysopen my $fh, $path, ORDWR                         or die $!;\n\nTo open file for update, create file if necessary:\n\nsysopen my $fh, $path, ORDWR|OCREAT                 or die $!;\nsysopen my $fh, $path, ORDWR|OCREAT, 0666           or die $!;\n\nTo open file for update, file must not exist:\n\nsysopen my $fh, $path, ORDWR|OEXCL|OCREAT          or die $!;\nsysopen my $fh, $path, ORDWR|OEXCL|OCREAT, 0666    or die $!;\n\nTo open a file without blocking, creating if necessary:\n\nsysopen my $fh, '/foo/somefile', OWRONLY|ONDELAY|OCREAT\nor die \"can't open /foo/somefile: $!\":\n\nBe warned that neither creation nor deletion of files is guaranteed to\nbe an atomic operation over NFS. That is, two processes might both\nsuccessfully create or unlink the same file! Therefore OEXCL isn't as\nexclusive as you might wish.\n\nSee also perlopentut.\n\nHow can I open a file named with a leading \">\" or trailing blanks?\n(contributed by Brian McCauley)\n\nThe special two-argument form of Perl's open() function ignores trailing\nblanks in filenames and infers the mode from certain leading characters\n(or a trailing \"|\"). In older versions of Perl this was the only version\nof open() and so it is prevalent in old code and books.\n\nUnless you have a particular reason to use the two-argument form you\nshould use the three-argument form of open() which does not treat any\ncharacters in the filename as special.\n\nopen my $fh, \"<\", \"  file  \";  # filename is \"   file   \"\nopen my $fh, \">\", \">file\";     # filename is \">file\"\n\nHow can I 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",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq6.pod": {
            "content": "How can I hope to use regular expressions without creating illegible and unmaintainable code?\nThree techniques can make regular expressions maintainable and\nunderstandable.\n\nComments Outside the Regex\nDescribe what you're doing and how you're doing it, using normal\nPerl comments.\n\n# turn the line into the first word, a colon, and the\n# number of characters on the rest of the line\ns/^(\\w+)(.*)/ lc($1) . \":\" . length($2) /meg;\n\nComments Inside the Regex\nThe \"/x\" modifier causes whitespace to be ignored in a regex pattern\n(except in a character class and a few other places), and also\nallows you to use normal comments there, too. As you can imagine,\nwhitespace and comments help a lot.\n\n\"/x\" lets you turn this:\n\ns{<(?:[^>'\"]*|\".*?\"|'.*?')+>}{}gs;\n\ninto this:\n\ns{ <                    # opening angle bracket\n(?:                 # Non-backreffing grouping paren\n[^>'\"] *        # 0 or more things that are neither > nor ' nor \"\n|           #    or else\n\".*?\"           # a section between double quotes (stingy match)\n|           #    or else\n'.*?'           # a section between single quotes (stingy match)\n) +                 #   all occurring one or more times\n>                   # closing angle bracket\n}{}gsx;                 # replace with nothing, i.e. delete\n\nIt's still not quite so clear as prose, but it is very useful for\ndescribing the meaning of each part of the pattern.\n\nDifferent Delimiters\nWhile we normally think of patterns as being delimited with \"/\"\ncharacters, they can be delimited by almost any character. perlre\ndescribes this. For example, the \"s///\" above uses braces as\ndelimiters. Selecting another delimiter can avoid quoting the\ndelimiter within the pattern:\n\ns/\\/usr\\/local/\\/usr\\/share/g;    # bad delimiter choice\ns#/usr/local#/usr/share#g;        # better\n\nUsing logically paired delimiters can be even more readable:\n\ns{/usr/local/}{/usr/share}g;      # better still\n\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\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\nWhy don't word-boundary searches with \"\\b\" work for me?\n(contributed by brian d foy)\n\nEnsure that you know what \\b really does: it's the boundary between a\nword character, \\w, and something that isn't a word character. That\nthing that isn't a word character might be \\W, but it can also be the\nstart or end of the string.\n\nIt's not (not!) the boundary between whitespace and non-whitespace, and\nit's not the stuff between words we use to create sentences.\n\nIn regex speak, a word boundary (\\b) is a \"zero width assertion\",\nmeaning that it doesn't represent a character in the string, but a\ncondition at a certain position.\n\nFor the regular expression, /\\bPerl\\b/, there has to be a word boundary\nbefore the \"P\" and after the \"l\". As long as something other than a word\ncharacter precedes the \"P\" and succeeds the \"l\", the pattern will match.\nThese strings match /\\bPerl\\b/.\n\n\"Perl\"    # no word char before \"P\" or after \"l\"\n\"Perl \"   # same as previous (space is not a word char)\n\"'Perl'\"  # the \"'\" char is not a word char\n\"Perl's\"  # no word char before \"P\", non-word char after \"l\"\n\nThese strings do not match /\\bPerl\\b/.\n\n\"Perl\"   # \"\" is a word char!\n\"Perler\"  # no word char before \"P\", but one after \"l\"\n\nYou don't have to use \\b to match words though. You can look for\nnon-word characters surrounded by word characters. These strings match\nthe pattern /\\b'\\b/.\n\n\"don't\"   # the \"'\" char is surrounded by \"n\" and \"t\"\n\"qep'a'\"  # the \"'\" char is surrounded by \"p\" and \"a\"\n\nThese strings do not match /\\b'\\b/.\n\n\"foo'\"    # there is no word char after non-word \"'\"\n\nYou can also use the complement of \\b, \\B, to specify that there should\nnot be a word boundary.\n\nIn the pattern /\\Bam\\B/, there must be a word character before the \"a\"\nand after the \"m\". These patterns match /\\Bam\\B/:\n\n\"llama\"   # \"am\" surrounded by word chars\n\"Samuel\"  # same\n\nThese strings do not match /\\Bam\\B/\n\n\"Sam\"      # no word boundary before \"a\", but one after \"m\"\n\"I am Sam\" # \"am\" surrounded by non-word chars\n\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 can I match strings with multibyte characters?\nStarting from Perl 5.6 Perl has had some level of multibyte character\nsupport. Perl 5.8 or later is recommended. Supported multibyte character\nrepertoires include Unicode, and legacy encodings through the Encode\nmodule. See perluniintro, perlunicode, and Encode.\n\nIf you are stuck with older Perls, you can do Unicode with the\nUnicode::String module, and character conversions using the\nUnicode::Map8 and Unicode::Map modules. If you are using Japanese\nencodings, you might try using the jperl 5.00503.\n\nFinally, the following set of approaches was offered by Jeffrey Friedl,\nwhose article in issue #5 of The Perl Journal talks about this very\nmatter.\n\nLet's suppose you have some weird Martian encoding where pairs of ASCII\nuppercase letters encode single Martian letters (i.e. the two bytes \"CV\"\nmake a single Martian letter, as do the two bytes \"SG\", \"VS\", \"XX\",\netc.). Other bytes represent single characters, just like ASCII.\n\nSo, the string of Martian \"I am CVSGXX!\" uses 12 bytes to encode the\nnine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.\n\nNow, say you want to search for the single character \"/GX/\". Perl\ndoesn't know about Martian, so it'll find the two bytes \"GX\" in the \"I\nam CVSGXX!\" string, even though that character isn't there: it just\nlooks like it is because \"SG\" is next to \"XX\", but there's no real \"GX\".\nThis is a big problem.\n\nHere are a few ways, all painful, to deal with it:\n\n# Make sure adjacent \"martian\" bytes are no longer adjacent.\n$martian =~ s/([A-Z][A-Z])/ $1 /g;\n\nprint \"found GX!\\n\" if $martian =~ /GX/;\n\nOr like this:\n\nmy @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;\n# above is conceptually similar to:     my @chars = $text =~ m/(.)/g;\n#\nforeach my $char (@chars) {\nprint \"found GX!\\n\", last if $char eq 'GX';\n}\n\nOr like this:\n\nwhile ($martian =~ m/\\G([A-Z][A-Z]|.)/gs) {  # \\G probably unneeded\nif ($1 eq 'GX') {\nprint \"found GX!\\n\";\nlast;\n}\n}\n\nHere's another, slightly less painful, way to do it from Benjamin\nGoldberg, who uses a zero-width negative look-behind assertion.\n\nprint \"found GX!\\n\" if    $martian =~ m/\n(?<![A-Z])\n(?:[A-Z][A-Z])*?\nGX\n/x;\n\nThis succeeds if the \"martian\" character GX is in the string, and fails\notherwise. If you don't like using (?<!), a zero-width negative\nlook-behind assertion, you can replace (?<![A-Z]) with (?:^|[^A-Z]).\n\nIt does have the drawback of putting the wrong thing in $-[0] and $+[0],\nbut this usually can be worked around.\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq7.pod": {
            "content": "What 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 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",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq8.pod": {
            "content": "How 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 read and write the serial port?\nThis depends on which operating system your program is running on. In\nthe case of Unix, the serial ports will be accessible through files in\n\"/dev\"; on other systems, device names will doubtless differ. Several\nproblem areas common to all device interaction are the following:\n\nlockfiles\nYour system may use lockfiles to control multiple access. Make sure\nyou follow the correct protocol. Unpredictable behavior can result\nfrom multiple processes reading from one device.\n\nopen mode\nIf you expect to use both read and write operations on the device,\nyou'll have to open it for update (see \"open\" in perlfunc for\ndetails). You may wish to open it without running the risk of\nblocking by using sysopen() and \"ORDWR|ONDELAY|ONOCTTY\" from the\nFcntl module (part of the standard perl distribution). See \"sysopen\"\nin perlfunc for more on this approach.\n\nend of line\nSome devices will be expecting a \"\\r\" at the end of each line rather\nthan a \"\\n\". In some ports of perl, \"\\r\" and \"\\n\" are different from\ntheir usual (Unix) ASCII values of \"\\015\" and \"\\012\". You may have\nto give the numeric values you want directly, using octal (\"\\015\"),\nhex (\"0x0D\"), or as a control-character specification (\"\\cM\").\n\nprint DEV \"atv1\\012\";    # wrong, for some devices\nprint DEV \"atv1\\015\";    # right, for some devices\n\nEven though with normal text files a \"\\n\" will do the trick, there\nis still no unified scheme for terminating a line that is portable\nbetween Unix, DOS/Win, and Macintosh, except to terminate *ALL* line\nends with \"\\015\\012\", and strip what you don't need from the output.\nThis applies especially to socket I/O and autoflushing, discussed\nnext.\n\nflushing output\nIf you expect characters to get to your device when you print()\nthem, you'll want to autoflush that filehandle. You can use select()\nand the $| variable to control autoflushing (see \"$|\" in perlvar and\n\"select\" in perlfunc, or perlfaq5, \"How do I flush/unbuffer an\noutput filehandle? Why must I do this?\"):\n\nmy $oldhandle = select($devfh);\n$| = 1;\nselect($oldhandle);\n\nYou'll also see code that does this without a temporary variable, as\nin\n\nselect((select($debhandle), $| = 1)[0]);\n\nOr if you don't mind pulling in a few thousand lines of code just\nbecause you're afraid of a little $| variable:\n\nuse IO::Handle;\n$devfh->autoflush(1);\n\nAs mentioned in the previous item, this still doesn't work when\nusing socket I/O between Unix and Macintosh. You'll need to hard\ncode your line terminators, in that case.\n\nnon-blocking input\nIf you are doing a blocking read() or sysread(), you'll have to\narrange for an alarm handler to provide a timeout (see \"alarm\" in\nperlfunc). If you have a non-blocking open, you'll likely have a\nnon-blocking read, which means you may have to use a 4-arg select()\nto determine whether I/O is ready on that device (see \"select\" in\nperlfunc.\n\nWhile trying to read from his caller-id box, the notorious Jamie\nZawinski \"<jwz@netscape.com>\", after much gnashing of teeth and fighting\nwith \"sysread\", \"sysopen\", POSIX's \"tcgetattr\" business, and various\nother functions that go bump in the night, finally came up with this:\n\nsub openmodem {\nuse IPC::Open2;\nmy $stty = `/bin/stty -g`;\nopen2( \\*MODEMIN, \\*MODEMOUT, \"cu -l$modemdevice -s2400 2>&1\");\n# starting cu hoses /dev/tty's stty settings, even when it has\n# been opened on a pipe...\nsystem(\"/bin/stty $stty\");\n$ = <MODEMIN>;\nchomp;\nif ( !m/^Connected/ ) {\nprint STDERR \"$0: cu printed `$' instead of `Connected'\\n\";\n}\n}\n\nHow can I do an atexit() or setjmp()/longjmp()? (Exception handling)\nYou can use the \"END\" block to simulate atexit(). Each package's \"END\"\nblock is called when the program or thread ends. See the perlmod manpage\nfor more details about \"END\" blocks.\n\nFor example, you can use this to make sure your filter program managed\nto finish its output without filling up the disk:\n\nEND {\nclose(STDOUT) || die \"stdout close failed: $!\";\n}\n\nThe \"END\" block isn't called when untrapped signals kill the program,\nthough, so if you use \"END\" blocks you should also use\n\nuse sigtrap qw(die normal-signals);\n\nPerl's exception-handling mechanism is its eval() operator. You can use",
            "subsections": [
                {
                    "name": "eval",
                    "content": "section on signals, especially the time-out handler for a blocking"
                },
                {
                    "name": "flock",
                    "content": "*Programming Perl*.\n\nIf exception handling is all you're interested in, use one of the many\nCPAN modules that handle exceptions, such as Try::Tiny.\n\nIf you want the atexit() syntax (and an rmexit() as well), try the\n\"AtExit\" module available from CPAN.\n\nWhy can't I get the output of a command with system()?\nYou're confusing the purpose of system() and backticks (``). system()\nruns a command and returns exit status information (as a 16 bit value:\nthe low 7 bits are the signal the process died from, if any, and the\nhigh 8 bits are the actual exit value). Backticks (``) run a command and\nreturn what it sent to STDOUT.\n\nmy $exitstatus   = system(\"mail-users\");\nmy $outputstring = `ls`;\n\nWhat's wrong with using backticks in a void context?\nStrictly speaking, nothing. Stylistically speaking, it's not a good way\nto write maintainable code. Perl has several operators for running\nexternal commands. Backticks are one; they collect the output from the\ncommand for use in your program. The \"system\" function is another; it\ndoesn't do this.\n\nWriting backticks in your program sends a clear message to the readers\nof your code that you wanted to collect the output of the command. Why\nsend a clear message that isn't true?\n\nConsider this line:\n\n`cat /etc/termcap`;\n\nYou forgot to check $? to see whether the program even ran correctly.\nEven if you wrote\n\nprint `cat /etc/termcap`;\n\nthis code could and probably should be written as\n\nsystem(\"cat /etc/termcap\") == 0\nor die \"cat program failed!\";\n\nwhich will echo the cat command's output as it is generated, instead of\nwaiting until the program has completed to print it out. It also checks\nthe return value.\n\n\"system\" also provides direct control over whether shell wildcard\nprocessing may take place, whereas backticks do not.\n\nHow can I call backticks without shell processing?\nThis is a bit tricky. You can't simply write the command like this:\n\n@ok = `grep @opts '$searchstring' @filenames`;\n\nAs of Perl 5.8.0, you can use open() with multiple arguments. Just like\nthe list forms of system() and exec(), no shell escapes happen.\n\nopen( GREP, \"-|\", 'grep', @opts, $searchstring, @filenames );\nchomp(@ok = <GREP>);\nclose GREP;\n\nYou can also:\n\nmy @ok = ();\nif (open(GREP, \"-|\")) {\nwhile (<GREP>) {\nchomp;\npush(@ok, $);\n}\nclose GREP;\n} else {\nexec 'grep', @opts, $searchstring, @filenames;\n}\n\nJust as with system(), no shell escapes happen when you exec() a list.\nFurther examples of this can be found in \"Safe Pipe Opens\" in perlipc.\n\nNote that if you're using Windows, no solution to this vexing issue is\neven possible. Even though Perl emulates fork(), you'll still be stuck,\nbecause Windows does not have an argc/argv-style API.\n\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\nHow can I write expect in Perl?\nOnce upon a time, there was a library called chat2.pl (part of the\nstandard perl distribution), which never really got finished. If you\nfind it somewhere, *don't use it*. These days, your best bet is to look\nat the Expect module available from CPAN, which also requires two other\nmodules from CPAN, IO::Pty and IO::Stty.\n\nI {changed directory, modified my environment} in a perl script. How come the change disappeared when I exited the script? How do I get my changes to be visible?\nUnix\nIn the strictest sense, it can't be done--the script executes as a\ndifferent process from the shell it was started from. Changes to a\nprocess are not reflected in its parent--only in any children\ncreated after the change. There is shell magic that may allow you to\nfake it by eval()ing the script's output in your shell; check out\nthe comp.unix.questions FAQ for details.\n\nHow do I close a process's filehandle without waiting for it to complete?\nAssuming your system supports such things, just send an appropriate\nsignal to the process (see \"kill\" in perlfunc). It's common to first\nsend a TERM signal, wait a little bit, and then send a KILL signal to\nfinish it off.\n\nHow do I set CPU limits?\n(contributed by Xho)\n\nUse the BSD::Resource module from CPAN. As an example:\n\nuse BSD::Resource;\nsetrlimit(RLIMITCPU,10,20) or die $!;\n\nThis sets the soft and hard limits to 10 and 20 seconds, respectively.\nAfter 10 seconds of time spent running on the CPU (not \"wall\" time), the\nprocess will be sent a signal (XCPU on some systems) which, if not\ntrapped, will cause the process to terminate. If that signal is trapped,\nthen after 10 more seconds (20 seconds in total) the process will be\nkilled with a non-trappable signal.\n\nSee the BSD::Resource and your systems documentation for the gory\ndetails.\n\nHow do I make a system() exit on control-C?\nYou can't. You need to imitate the system() call (see perlipc for sample\ncode) and then have a signal handler for the INT signal that passes the\nsignal on to the subprocess. Or you can check for it:\n\n$rc = system($cmd);\nif ($rc & 127) { die \"signal death\" }\n\nHow do I open a file without blocking?\nIf you're lucky enough to be using a system that supports non-blocking\nreads (most Unixish systems do), you need only to use the \"ONDELAY\" or\n\"ONONBLOCK\" flag from the \"Fcntl\" module in conjunction with sysopen():\n\nuse Fcntl;\nsysopen(my $fh, \"/foo/somefile\", OWRONLY|ONDELAY|OCREAT, 0644)\nor die \"can't open /foo/somefile: $!\":\n\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"
                }
            ]
        }
    },
    "flags": [],
    "examples": [],
    "see_also": []
}