{
    "mode": "perldoc",
    "parameter": "ST",
    "section": "-q",
    "url": "https://www.chedong.com/phpMan.php/perldoc/ST/json",
    "generated": "2026-10-05T05:15:52Z",
    "sections": {
        "Found in /usr/share/perl/5.38/pod/perlfaq1.pod": {
            "content": "How stable is Perl?\nProduction releases, which incorporate bug fixes and new functionality,\nare widely tested before release. Since the 5.000 release, we have\naveraged about one production release per year.\n\nThe Perl development team occasionally make changes to the internal core\nof the language, but all possible efforts are made toward backward\ncompatibility.\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq2.pod": {
            "content": "Where 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\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",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq3.pod": {
            "content": "How do I find which modules are installed on my system?\nFrom the command line, you can use the \"cpan\" command's \"-l\" switch:\n\n$ cpan -l\n\nYou can also use \"cpan\"'s \"-a\" switch to create an autobundle file that\n\"CPAN.pm\" understands and can use to re-install every module:\n\n$ cpan -a\n\nInside a Perl program, you can use the ExtUtils::Installed module to\nshow all installed distributions, although it can take awhile to do its\nmagic. The standard library which comes with Perl just shows up as\n\"Perl\" (although you can get those with Module::CoreList).\n\nuse ExtUtils::Installed;\n\nmy $inst    = ExtUtils::Installed->new();\nmy @modules = $inst->modules();\n\nIf you want a list of all of the Perl module filenames, you can use\nFile::Find::Rule:\n\nuse File::Find::Rule;\n\nmy @files = File::Find::Rule->\nextras({follow => 1})->\nfile()->\nname( '*.pm' )->\nin( @INC )\n;\n\nIf you do not have that module, you can do the same thing with\nFile::Find which is part of the standard library:\n\nuse File::Find;\nmy @files;\n\nfind(\n{\nwanted => sub {\npush @files, $File::Find::fullname\nif -f $File::Find::fullname && /\\.pm$/\n},\nfollow => 1,\nfollowskip => 2,\n},\n@INC\n);\n\nprint join \"\\n\", @files;\n\nIf you simply need to check quickly to see if a module is available, you\ncan check for its documentation. If you can read the documentation the\nmodule is most likely installed. If you cannot read the documentation,\nthe module might not have any (in rare cases):\n\n$ perldoc Module::Name\n\nYou can also try to include the module in a one-liner to see if perl\nfinds it:\n\n$ perl -MModule::Name -e1\n\n(If you don't receive a \"Can't locate ... in @INC\" error message, then\nPerl found the module name you asked for.)\n\nHow can I make my Perl program run faster?\nThe best way to do this is to come up with a better algorithm. This can\noften make a dramatic difference. Jon Bentley's book *Programming\nPearls* (that's not a misspelling!) has some good tips on optimization,\ntoo. Advice on benchmarking boils down to: benchmark and profile to make\nsure you're optimizing the right part, look for better algorithms\ninstead of microtuning your code, and when all else fails consider just\nbuying faster hardware. You will probably want to read the answer to the\nearlier question \"How do I profile my Perl programs?\" if you haven't\ndone so already.\n\nA different approach is to autoload seldom-used Perl code. See the\nAutoSplit and AutoLoader modules in the standard distribution for that.\nOr you could locate the bottleneck and think about writing just that\npart in C, the way we used to take bottlenecks in C code and write them\nin assembler. Similar to rewriting in C, modules that have critical\nsections can be written in C (for instance, the PDL module from CPAN).\n\nIf you're currently linking your perl executable to a shared *libc.so*,\nyou can often gain a 10-25% performance benefit by rebuilding it to link\nwith a static libc.a instead. This will make a bigger perl executable,\nbut your Perl programs (and programmers) may thank you for it. See the\nINSTALL file in the source distribution for more information.\n\nThe undump program was an ancient attempt to speed up Perl program by\nstoring the already-compiled form to disk. This is no longer a viable\noption, as it only worked on a few architectures, and wasn't a good\nsolution anyway.\n\nWhy don't Perl one-liners work on my DOS/Mac/VMS system?\nThe problem is usually that the command interpreters on those systems\nhave rather different ideas about quoting than the Unix shells under\nwhich the one-liners were created. On some systems, you may have to\nchange single-quotes to double ones, which you must *NOT* do on Unix or\nPlan9 systems. You might also have to change a single % to a %%.\n\nFor example:\n\n# Unix (including Mac OS X)\nperl -e 'print \"Hello world\\n\"'\n\n# DOS, etc.\nperl -e \"print \\\"Hello world\\n\\\"\"\n\n# Mac Classic\nprint \"Hello world\\n\"\n(then Run \"Myscript\" or Shift-Command-R)\n\n# MPW\nperl -e 'print \"Hello world\\n\"'\n\n# VMS\nperl -e \"print \"\"Hello world\\n\"\"\"\n\nThe problem is that none of these examples are reliable: they depend on\nthe command interpreter. Under Unix, the first two often work. Under\nDOS, it's entirely possible that neither works. If 4DOS was the command\nshell, you'd probably have better luck like this:\n\nperl -e \"print <Ctrl-x>\"Hello world\\n<Ctrl-x>\"\"\n\nUnder the Mac, it depends which environment you are using. The MacPerl\nshell, or MPW, is much like Unix shells in its support for several\nquoting variants, except that it makes free use of the Mac's non-ASCII\ncharacters as control characters.\n\nUsing qq(), q(), and qx(), instead of \"double quotes\", 'single quotes',\nand `backticks`, may make one-liners easier to write.\n\nThere is no general solution to all of this. It is a mess.\n\n[Some of this answer was contributed by Kenneth Albanowski.]\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq4.pod": {
            "content": "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?\nFor the long explanation, see David Goldberg's \"What Every Computer\nScientist Should Know About Floating-Point Arithmetic\"\n(<http://web.cse.msu.edu/~cse320/Documents/FloatingPoint.pdf>).\n\nInternally, your computer represents floating-point numbers in binary.\nDigital (as in powers of two) computers cannot store all numbers\nexactly. Some real numbers lose precision in the process. This is a\nproblem with how computers store numbers and affects all computer\nlanguages, not just Perl.\n\nperlnumber shows the gory details of number representations and\nconversions.\n\nTo limit the number of decimal places in your numbers, you can use the\n\"printf\" or \"sprintf\" function. See \"Floating-point Arithmetic\" in\nperlop for more details.\n\nprintf \"%.2f\", 10/3;\n\nmy $number = sprintf \"%.2f\", 10/3;\n\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 do I find yesterday's date?\n(contributed by brian d foy)\n\nTo do it correctly, you can use one of the \"Date\" modules since they\nwork with calendars instead of times. The DateTime module makes it\nsimple, and give you the same time of day, only the day before, despite\ndaylight saving time changes:\n\nuse DateTime;\n\nmy $yesterday = DateTime->now->subtract( days => 1 );\n\nprint \"Yesterday was $yesterday\\n\";\n\nYou can also use the Date::Calc module using its \"TodayandNow\"\nfunction.\n\nuse Date::Calc qw( TodayandNow AddDeltaDHMS );\n\nmy @datetime = AddDeltaDHMS( TodayandNow(), -1, 0, 0, 0 );\n\nprint \"@datetime\\n\";\n\nMost people try to use the time rather than the calendar to figure out\ndates, but that assumes that days are twenty-four hours each. For most\npeople, there are two days a year when they aren't: the switch to and\nfrom summer time throws this off. For example, the rest of the\nsuggestions will be wrong sometimes:\n\nStarting with Perl 5.10, Time::Piece and Time::Seconds are part of the\nstandard distribution, so you might think that you could do something\nlike this:\n\nuse Time::Piece;\nuse Time::Seconds;\n\nmy $yesterday = localtime() - ONEDAY; # WRONG\nprint \"Yesterday was $yesterday\\n\";\n\nThe Time::Piece module exports a new \"localtime\" that returns an object,\nand Time::Seconds exports the \"ONEDAY\" constant that is a set number of\nseconds. This means that it always gives the time 24 hours ago, which is\nnot always yesterday. This can cause problems around the end of daylight\nsaving time when there's one day that is 25 hours long.\n\nYou have the same problem with Time::Local, which will give the wrong\nanswer for those same special cases:\n\n# contributed by Gunnar Hjalmarsson\nuse Time::Local;\nmy $today = timelocal 0, 0, 12, ( localtime )[3..5];\nmy ($d, $m, $y) = ( localtime $today-86400 )[3..5]; # WRONG\nprintf \"Yesterday: %d-%02d-%02d\\n\", $y+1900, $m+1, $d;\n\nHow do I unescape a string?\nIt depends just what you mean by \"escape\". URL escapes are dealt with in\nperlfaq9. Shell escapes with the backslash (\"\\\") character are removed\nwith\n\ns/\\\\(.)/$1/g;\n\nThis won't expand \"\\n\" or \"\\t\" or any other special escapes.\n\nHow do I expand function calls in a string?\n(contributed by brian d foy)\n\nThis is documented in perlref, and although it's not the easiest thing\nto read, it does work. In each of these examples, we call the function\ninside the braces used to dereference a reference. If we have more than\none return value, we can construct and dereference an anonymous array.\nIn this case, we call the function in list context.\n\nprint \"The time values are @{ [localtime] }.\\n\";\n\nIf we want to call the function in scalar context, we have to do a bit\nmore work. We can really have any code we like inside the braces, so we\nsimply have to end with the scalar reference, although how you do that\nis up to you, and you can use code inside the braces. Note that the use\nof parens creates a list context, so we need \"scalar\" to force the\nscalar context on the function:\n\nprint \"The time is ${\\(scalar localtime)}.\\n\"\n\nprint \"The time is ${ my $x = localtime; \\$x }.\\n\";\n\nIf your function already returns a reference, you don't need to create\nthe reference yourself.\n\nsub timestamp { my $t = localtime; \\$t }\n\nprint \"The time is ${ timestamp() }.\\n\";\n\nThe \"Interpolation\" module can also do a lot of magic for you. You can\nspecify a variable name, in this case \"E\", to set up a tied hash that\ndoes the interpolation for you. It has several other methods to do this\nas well.\n\nuse Interpolation E => 'eval';\nprint \"The time values are $E{localtime()}.\\n\";\n\nIn most cases, it is probably easier to simply use string concatenation,\nwhich also forces scalar context.\n\nprint \"The time is \" . localtime() . \".\\n\";\n\nHow do I find matching/nesting anything?\nTo find something between two single characters, a pattern like\n\"/x([^x]*)x/\" will get the intervening bits in $1. For multiple ones,\nthen something more like \"/alpha(.*?)omega/\" would be needed. For nested\npatterns and/or balanced expressions, see the so-called (?PARNO)\nconstruct (available since perl 5.10). The CPAN module Regexp::Common\ncan help to build such regular expressions (see in particular\nRegexp::Common::balanced and Regexp::Common::delimited).\n\nMore complex cases will require to write a parser, probably using a\nparsing module from CPAN, like Regexp::Grammars, Parse::RecDescent,\nParse::Yapp, Text::Balanced, or Marpa::R2.\n\nHow do I reverse a string?\nUse reverse() in scalar context, as documented in \"reverse\" in perlfunc.\n\nmy $reversed = reverse $string;\n\nHow do I expand tabs in a string?\nYou can do it yourself:\n\n1 while $string =~ s/\\t+/' ' x (length($&) * 8 - length($`) % 8)/e;\n\nOr you can just use the Text::Tabs module (part of the standard Perl\ndistribution).\n\nuse Text::Tabs;\nmy @expandedlines = expand(@lineswithtabs);\n\nHow can I access or change N characters of a string?\nYou can access the first characters of a string with substr(). To get\nthe first character, for example, start at position 0 and grab the\nstring of length 1.\n\nmy $string = \"Just another Perl Hacker\";\nmy $firstchar = substr( $string, 0, 1 );  #  'J'\n\nTo change part of a string, you can use the optional fourth argument\nwhich is the replacement string.\n\nsubstr( $string, 13, 4, \"Perl 5.8.0\" );\n\nYou can also use substr() as an lvalue.\n\nsubstr( $string, 13, 4 ) =  \"Perl 5.8.0\";\n\nHow 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 can I split a [character]-delimited string except when inside [character]?\nSeveral modules can handle this sort of parsing--Text::Balanced,\nText::CSV, Text::CSVXS, and Text::ParseWords, among others.\n\nTake the example case of trying to split a string that is\ncomma-separated into its different fields. You can't use \"split(/,/)\"\nbecause you shouldn't split if the comma is inside quotes. For example,\ntake a data line like this:\n\nSAR001,\"\",\"Cimetrix, Inc\",\"Bob Smith\",\"CAM\",N,8,1,0,7,\"Error, Core Dumped\"\n\nDue to the restriction of the quotes, this is a fairly complex problem.\nThankfully, we have Jeffrey Friedl, author of *Mastering Regular\nExpressions*, to handle these for us. He suggests (assuming your string\nis contained in $text):\n\nmy @new = ();\npush(@new, $+) while $text =~ m{\n\"([^\\\"\\\\]*(?:\\\\.[^\\\"\\\\]*)*)\",? # groups the phrase inside the quotes\n| ([^,]+),?\n| ,\n}gx;\npush(@new, undef) if substr($text,-1,1) eq ',';\n\nIf you want to represent quotation marks inside a\nquotation-mark-delimited field, escape them with backslashes (eg, \"like\n\\\"this\\\"\".\n\nAlternatively, the Text::ParseWords module (part of the standard Perl\ndistribution) lets you say:\n\nuse Text::ParseWords;\n@new = quotewords(\",\", 0, $text);\n\nFor parsing or generating CSV, though, using Text::CSV rather than\nimplementing it yourself is highly recommended; you'll save yourself odd\nbugs popping up later by just using code which has already been tried\nand tested in production for years.\n\nHow do I strip blank space from the beginning/end of a string?\n(contributed by brian d foy)\n\nA substitution can do this for you. For a single line, you want to\nreplace all the leading or trailing whitespace with nothing. You can do\nthat with a pair of substitutions:\n\ns/^\\s+//;\ns/\\s+$//;\n\nYou can also write that as a single substitution, although it turns out\nthe combined statement is slower than the separate ones. That might not\nmatter to you, though:\n\ns/^\\s+|\\s+$//g;\n\nIn this regular expression, the alternation matches either at the\nbeginning or the end of the string since the anchors have a lower\nprecedence than the alternation. With the \"/g\" flag, the substitution\nmakes all possible matches, so it gets both. Remember, the trailing\nnewline matches the \"\\s+\", and the \"$\" anchor can match to the absolute\nend of the string, so the newline disappears too. Just add the newline\nto the output, which has the added benefit of preserving \"blank\"\n(consisting entirely of whitespace) lines which the \"^\\s+\" would remove\nall by itself:\n\nwhile( <> ) {\ns/^\\s+|\\s+$//g;\nprint \"$\\n\";\n}\n\nFor a multi-line string, you can apply the regular expression to each\nlogical line in the string by adding the \"/m\" flag (for \"multi-line\").\nWith the \"/m\" flag, the \"$\" matches *before* an embedded newline, so it\ndoesn't remove it. This pattern still removes the newline at the end of\nthe string:\n\n$string =~ s/^\\s+|\\s+$//gm;\n\nRemember that lines consisting entirely of whitespace will disappear,\nsince the first part of the alternation can match the entire string and\nreplace it with nothing. If you need to keep embedded blank lines, you\nhave to do a little more work. Instead of matching any whitespace (since\nthat includes a newline), just match the other whitespace:\n\n$string =~ s/^[\\t\\f ]+|[\\t\\f ]+$//mg;\n\nHow do I pad a string with blanks or pad a number with zeroes?\nIn the following examples, $padlen is the length to which you wish to\npad the string, $text or $num contains the string to be padded, and\n$padchar contains the padding character. You can use a single character\nstring constant instead of the $padchar variable if you know what it is\nin advance. And in the same way you can use an integer in place of\n$padlen if you know the pad length in advance.\n\nThe simplest method uses the \"sprintf\" function. It can pad on the left\nor right with blanks and on the left with zeroes and it will not\ntruncate the result. The \"pack\" function can only pad strings on the\nright with blanks and it will truncate the result to a maximum length of\n$padlen.\n\n# Left padding a string with blanks (no truncation):\nmy $padded = sprintf(\"%${padlen}s\", $text);\nmy $padded = sprintf(\"%*s\", $padlen, $text);  # same thing\n\n# Right padding a string with blanks (no truncation):\nmy $padded = sprintf(\"%-${padlen}s\", $text);\nmy $padded = sprintf(\"%-*s\", $padlen, $text); # same thing\n\n# Left padding a number with 0 (no truncation):\nmy $padded = sprintf(\"%0${padlen}d\", $num);\nmy $padded = sprintf(\"%0*d\", $padlen, $num); # same thing\n\n# Right padding a string with blanks using pack (will truncate):\nmy $padded = pack(\"A$padlen\",$text);\n\nIf you need to pad with a character other than blank or zero you can use\none of the following methods. They all generate a pad string with the\n\"x\" operator and combine that with $text. These methods do not truncate\n$text.\n\nLeft and right padding with any character, creating a new string:\n\nmy $padded = $padchar x ( $padlen - length( $text ) ) . $text;\nmy $padded = $text . $padchar x ( $padlen - length( $text ) );\n\nLeft and right padding with any character, modifying $text directly:\n\nsubstr( $text, 0, 0 ) = $padchar x ( $padlen - length( $text ) );\n$text .= $padchar x ( $padlen - length( $text ) );\n\nHow do I extract selected columns from a string?\n(contributed by brian d foy)\n\nIf you know the columns that contain the data, you can use \"substr\" to\nextract a single column.\n\nmy $column = substr( $line, $startcolumn, $length );\n\nYou can use \"split\" if the columns are separated by whitespace or some\nother delimiter, as long as whitespace or the delimiter cannot appear as\npart of the data.\n\nmy $line    = ' fred barney   betty   ';\nmy @columns = split /\\s+/, $line;\n# ( '', 'fred', 'barney', 'betty' );\n\nmy $line    = 'fred||barney||betty';\nmy @columns = split /\\|/, $line;\n# ( 'fred', '', 'barney', '', 'betty' );\n\nIf you want to work with comma-separated values, don't do this since\nthat format is a bit more complicated. Use one of the modules that\nhandle that format, such as Text::CSV, Text::CSVXS, or Text::CSVPP.\n\nIf you want to break apart an entire line of fixed columns, you can use\n\"unpack\" with the A (ASCII) format. By using a number after the format\nspecifier, you can denote the column width. See the \"pack\" and \"unpack\"\nentries in perlfunc for more details.\n\nmy @fields = unpack( $line, \"A8 A8 A8 A16 A4\" );\n\nNote that spaces in the format argument to \"unpack\" do not denote\nliteral spaces. If you have space separated data, you may want \"split\"\ninstead.\n\nHow do I find the soundex value of a string?\n(contributed by brian d foy)\n\nYou can use the \"Text::Soundex\" module. If you want to do fuzzy or close\nmatching, you might also try the String::Approx, and Text::Metaphone,\nand Text::DoubleMetaphone modules.\n\nHow can I expand variables in text strings?\n(contributed by brian d foy)\n\nIf you can avoid it, don't, or if you can use a templating system, such\nas Text::Template or Template Toolkit, do that instead. You might even\nbe able to get the job done with \"sprintf\" or \"printf\":\n\nmy $string = sprintf 'Say hello to %s and %s', $foo, $bar;\n\nHowever, for the one-off simple case where I don't want to pull out a\nfull templating system, I'll use a string that has two Perl scalar\nvariables in it. In this example, I want to expand $foo and $bar to\ntheir variable's values:\n\nmy $foo = 'Fred';\nmy $bar = 'Barney';\n$string = 'Say hello to $foo and $bar';\n\nOne way I can do this involves the substitution operator and a double\n\"/e\" flag. The first \"/e\" evaluates $1 on the replacement side and turns\nit into $foo. The second /e starts with $foo and replaces it with its\nvalue. $foo, then, turns into 'Fred', and that's finally what's left in\nthe string:\n\n$string =~ s/(\\$\\w+)/$1/eeg; # 'Say hello to Fred and Barney'\n\nThe \"/e\" will also silently ignore violations of strict, replacing\nundefined variable names with the empty string. Since I'm using the \"/e\"\nflag (twice even!), I have all of the same security problems I have with\n\"eval\" in its string form. If there's something odd in $foo, perhaps\nsomething like \"@{[ system \"rm -rf /\" ]}\", then I could get myself in\ntrouble.\n\nTo get around the security problem, I could also pull the values from a\nhash instead of evaluating variable names. Using a single \"/e\", I can\ncheck the hash to ensure the value exists, and if it doesn't, I can\nreplace the missing value with a marker, in this case \"???\" to signal\nthat I missed something:\n\nmy $string = 'This has $foo and $bar';\n\nmy %Replacements = (\nfoo  => 'Fred',\n);\n\n# $string =~ s/\\$(\\w+)/$Replacements{$1}/g;\n$string =~ s/\\$(\\w+)/\nexists $Replacements{$1} ? $Replacements{$1} : '???'\n/eg;\n\nprint $string;\n\nDoes Perl have anything like Ruby's #{} or Python's f string?\nUnlike the others, Perl allows you to embed a variable naked in a double\nquoted string, e.g. \"variable $variable\". When there isn't whitespace or\nother non-word characters following the variable name, you can add\nbraces (e.g. \"foo ${foo}bar\") to ensure correct parsing.\n\nAn array can also be embedded directly in a string, and will be expanded\nby default with spaces between the elements. The default LISTSEPARATOR\ncan be changed by assigning a different string to the special variable\n$\", such as \"local $\" = ', ';\".\n\nPerl also supports references within a string providing the equivalent\nof the features in the other two languages.\n\n\"${\\ ... }\" embedded within a string will work for most simple\nstatements such as an object->method call. More complex code can be\nwrapped in a do block \"${\\ do{...} }\".\n\nWhen you want a list to be expanded per $\", use \"@{[ ... ]}\".\n\nuse Time::Piece;\nuse Time::Seconds;\nmy $scalar = 'STRING';\nmy @array = ( 'zorro', 'a', 1, 'B', 3 );\n\n# Print the current date and time and then Tommorrow\nmy $t = Time::Piece->new;\nsay \"Now is: ${\\ $t->cdate() }\";\nsay \"Tomorrow: ${\\ do{ my $T=Time::Piece->new + ONEDAY ; $T->fullday }}\";\n\n# some variables in strings\nsay \"This is some scalar I have $scalar, this is an array @array.\";\nsay \"You can also write it like this ${scalar} @{array}.\";\n\n# Change the $LISTSEPARATOR\nlocal $\" = ':';\nsay \"Set \\$\\\" to delimit with ':' and sort the Array @{[ sort @array ]}\";\n\nYou may also want to look at the module Quote::Code, and templating\ntools such as Template::Toolkit and Mojo::Template.\n\nSee also: \"How can I expand variables in text strings?\" and \"How do I\nexpand function calls in a string?\" in this FAQ.\n\nWhat is the difference between a list and an array?\n(contributed by brian d foy)\n\nA list is a fixed collection of scalars. An array is a variable that\nholds a variable collection of scalars. An array can supply its\ncollection for list operations, so list operations also work on arrays:\n\n# slices\n( 'dog', 'cat', 'bird' )[2,3];\n@animals[2,3];\n\n# iteration\nforeach ( qw( dog cat bird ) ) { ... }\nforeach ( @animals ) { ... }\n\nmy @three = grep { length == 3 } qw( dog cat bird );\nmy @three = grep { length == 3 } @animals;\n\n# supply an argument list\nwashanimals( qw( dog cat bird ) );\nwashanimals( @animals );\n\nArray operations, which change the scalars, rearrange them, or add or\nsubtract some scalars, only work on arrays. These can't work on a list,\nwhich is fixed. Array operations include \"shift\", \"unshift\", \"push\",\n\"pop\", and \"splice\".\n\nAn array can also change its length:\n\n$#animals = 1;  # truncate to two elements\n$#animals = 10000; # pre-extend to 10,001 elements\n\nYou can change an array element, but you can't change a list element:\n\n$animals[0] = 'Rottweiler';\nqw( dog cat bird )[0] = 'Rottweiler'; # syntax error!\n\nforeach ( @animals ) {\ns/^d/fr/;  # works fine\n}\n\nforeach ( qw( dog cat bird ) ) {\ns/^d/fr/;  # Error! Modification of read only value!\n}\n\nHowever, if the list element is itself a variable, it appears that you\ncan change a list element. However, the list element is the variable,\nnot the data. You're not changing the list element, but something the\nlist element refers to. The list element itself doesn't change: it's\nstill the same variable.\n\nYou also have to be careful about context. You can assign an array to a\nscalar to get the number of elements in the array. This only works for\narrays, though:\n\nmy $count = @animals;  # only works with arrays\n\nIf you try to do the same thing with what you think is a list, you get a\nquite different result. Although it looks like you have a list on the\nrighthand side, Perl actually sees a bunch of scalars separated by a\ncomma:\n\nmy $scalar = ( 'dog', 'cat', 'bird' );  # $scalar gets bird\n\nSince you're assigning to a scalar, the righthand side is in scalar\ncontext. The comma operator (yes, it's an operator!) in scalar context\nevaluates its lefthand side, throws away the result, and evaluates it's\nrighthand side and returns the result. In effect, that list-lookalike\nassigns to $scalar it's rightmost value. Many people mess this up\nbecause they choose a list-lookalike whose last element is also the\ncount they expect:\n\nmy $scalar = ( 1, 2, 3 );  # $scalar gets 3, accidentally\n\nHow can I remove duplicate elements from a list or array?\n(contributed by brian d foy)\n\nUse a hash. When you think the words \"unique\" or \"duplicated\", think\n\"hash keys\".\n\nIf you don't care about the order of the elements, you could just create\nthe hash then extract the keys. It's not important how you create that\nhash: just that you use \"keys\" to get the unique elements.\n\nmy %hash   = map { $, 1 } @array;\n# or a hash slice: @hash{ @array } = ();\n# or a foreach: $hash{$} = 1 foreach ( @array );\n\nmy @unique = keys %hash;\n\nIf you want to use a module, try the \"uniq\" function from\nList::MoreUtils. In list context it returns the unique elements,\npreserving their order in the list. In scalar context, it returns the\nnumber of unique elements.\n\nuse List::MoreUtils qw(uniq);\n\nmy @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7\nmy $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7\n\nYou can also go through each element and skip the ones you've seen\nbefore. Use a hash to keep track. The first time the loop sees an\nelement, that element has no key in %Seen. The \"next\" statement creates\nthe key and immediately uses its value, which is \"undef\", so the loop\ncontinues to the \"push\" and increments the value for that key. The next\ntime the loop sees that same element, its key exists in the hash *and*\nthe value for that key is true (since it's not 0 or \"undef\"), so the\nnext skips that iteration and the loop goes to the next element.\n\nmy @unique = ();\nmy %seen   = ();\n\nforeach my $elem ( @array ) {\nnext if $seen{ $elem }++;\npush @unique, $elem;\n}\n\nYou can write this more briefly using a grep, which does the same thing.\n\nmy %seen = ();\nmy @unique = grep { ! $seen{ $ }++ } @array;\n\nHow can I tell whether a certain element is contained in a list or array?\n(portions of this answer contributed by Anno Siegel and brian d foy)\n\nHearing the word \"in\" is an *in*dication that you probably should have\nused a hash, not a list or array, to store your data. Hashes are\ndesigned to answer this question quickly and efficiently. Arrays aren't.\n\nThat being said, there are several ways to approach this. If you are\ngoing to make this query many times over arbitrary string values, the\nfastest way is probably to invert the original array and maintain a hash\nwhose keys are the first array's values:\n\nmy @blues = qw/azure cerulean teal turquoise lapis-lazuli/;\nmy %isblue = ();\nfor (@blues) { $isblue{$} = 1 }\n\nNow you can check whether $isblue{$somecolor}. It might have been a\ngood idea to keep the blues all in a hash in the first place.\n\nIf the values are all small integers, you could use a simple indexed\narray. This kind of an array will take up less space:\n\nmy @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);\nmy @istinyprime = ();\nfor (@primes) { $istinyprime[$] = 1 }\n# or simply  @istinyprime[@primes] = (1) x @primes;\n\nNow you check whether $istinyprime[$somenumber].\n\nIf the values in question are integers instead of strings, you can save\nquite a lot of space by using bit strings instead:\n\nmy @articles = ( 1..10, 150..2000, 2017 );\nundef $read;\nfor (@articles) { vec($read,$,1) = 1 }\n\nNow check whether \"vec($read,$n,1)\" is true for some $n.\n\nThese methods guarantee fast individual tests but require a\nre-organization of the original list or array. They only pay off if you\nhave to test multiple values against the same array.\n\nIf you are testing only once, the standard module List::Util exports the\nfunction \"any\" for this purpose. It works by stopping once it finds the\nelement. It's written in C for speed, and its Perl equivalent looks like\nthis subroutine:\n\nsub any (&@) {\nmy $code = shift;\nforeach (@) {\nreturn 1 if $code->();\n}\nreturn 0;\n}\n\nIf speed is of little concern, the common idiom uses grep in scalar\ncontext (which returns the number of items that passed its condition) to\ntraverse the entire list. This does have the benefit of telling you how\nmany matches it found, though.\n\nmy $isthere = grep $ eq $whatever, @array;\n\nIf you want to actually extract the matching elements, simply use grep\nin list context.\n\nmy @matches = grep $ eq $whatever, @array;\n\nHow do I test whether two arrays or hashes are equal?\nThe following code works for single-level arrays. It uses a stringwise\ncomparison, and does not distinguish defined versus undefined empty\nstrings. Modify if you have other needs.\n\n$areequal = comparearrays(\\@frogs, \\@toads);\n\nsub comparearrays {\nmy ($first, $second) = @;\nno warnings;  # silence spurious -w undef complaints\nreturn 0 unless @$first == @$second;\nfor (my $i = 0; $i < @$first; $i++) {\nreturn 0 if $first->[$i] ne $second->[$i];\n}\nreturn 1;\n}\n\nFor multilevel structures, you may wish to use an approach more like\nthis one. It uses the CPAN module FreezeThaw:\n\nuse FreezeThaw qw(cmpStr);\nmy @a = my @b = ( \"this\", \"that\", [ \"more\", \"stuff\" ] );\n\nprintf \"a and b contain %s arrays\\n\",\ncmpStr(\\@a, \\@b) == 0\n? \"the same\"\n: \"different\";\n\nThis approach also works for comparing hashes. Here we'll demonstrate\ntwo different answers:\n\nuse FreezeThaw qw(cmpStr cmpStrHard);\n\nmy %a = my %b = ( \"this\" => \"that\", \"extra\" => [ \"more\", \"stuff\" ] );\n$a{EXTRA} = \\%b;\n$b{EXTRA} = \\%a;\n\nprintf \"a and b contain %s hashes\\n\",\ncmpStr(\\%a, \\%b) == 0 ? \"the same\" : \"different\";\n\nprintf \"a and b contain %s hashes\\n\",\ncmpStrHard(\\%a, \\%b) == 0 ? \"the same\" : \"different\";\n\nThe first reports that both those the hashes contain the same data,\nwhile the second reports that they do not. Which you prefer is left as\nan exercise to the reader.\n\nHow do I find the first array element for which a condition is true?\nTo find the first array element which satisfies a condition, you can use\nthe first() function in the List::Util module, which comes with Perl\n5.8. This example finds the first element that contains \"Perl\".\n\nuse List::Util qw(first);\n\nmy $element = first { /Perl/ } @array;\n\nIf you cannot use List::Util, you can make your own loop to do the same\nthing. Once you find the element, you stop the loop with last.\n\nmy $found;\nforeach ( @array ) {\nif( /Perl/ ) { $found = $; last }\n}\n\nIf you want the array index, use the firstidx() function from\n\"List::MoreUtils\":\n\nuse List::MoreUtils qw(firstidx);\nmy $index = firstidx { /Perl/ } @array;\n\nOr write it yourself, iterating through the indices and checking the\narray element at each index until you find one that satisfies the\ncondition:\n\nmy( $found, $index ) = ( undef, -1 );\nfor( $i = 0; $i < @array; $i++ ) {\nif( $array[$i] =~ /Perl/ ) {\n$found = $array[$i];\n$index = $i;\nlast;\n}\n}\n\nHow do I handle linked lists?\n(contributed by brian d foy)\n\nPerl's arrays do not have a fixed size, so you don't need linked lists\nif you just want to add or remove items. You can use array operations\nsuch as \"push\", \"pop\", \"shift\", \"unshift\", or \"splice\" to do that.\n\nSometimes, however, linked lists can be useful in situations where you\nwant to \"shard\" an array so you have many small arrays instead of a\nsingle big array. You can keep arrays longer than Perl's largest array\nindex, lock smaller arrays separately in threaded programs, reallocate\nless memory, or quickly insert elements in the middle of the chain.\n\nSteve Lembark goes through the details in his YAPC::NA 2009 talk \"Perly\nLinked Lists\" ( <http://www.slideshare.net/lembark/perly-linked-lists>\n), although you can just use his LinkedList::Single module.\n\nHow do I handle circular lists?\n(contributed by brian d foy)\n\nIf you want to cycle through an array endlessly, you can increment the\nindex modulo the number of elements in the array:\n\nmy @array = qw( a b c );\nmy $i = 0;\n\nwhile( 1 ) {\nprint $array[ $i++ % @array ], \"\\n\";\nlast if $i > 20;\n}\n\nYou can also use Tie::Cycle to use a scalar that always has the next\nelement of the circular array:\n\nuse Tie::Cycle;\n\ntie my $cycle, 'Tie::Cycle', [ qw( FFFFFF 000000 FFFF00 ) ];\n\nprint $cycle; # FFFFFF\nprint $cycle; # 000000\nprint $cycle; # FFFF00\n\nThe Array::Iterator::Circular creates an iterator object for circular\narrays:\n\nuse Array::Iterator::Circular;\n\nmy $coloriterator = Array::Iterator::Circular->new(\nqw(red green blue orange)\n);\n\nforeach ( 1 .. 20 ) {\nprint $coloriterator->next, \"\\n\";\n}\n\nHow do I permute N elements of a list?\nUse the List::Permutor module on CPAN. If the list is actually an array,\ntry the Algorithm::Permute module (also on CPAN). It's written in XS\ncode and is very efficient:\n\nuse Algorithm::Permute;\n\nmy @array = 'a'..'d';\nmy $piterator = Algorithm::Permute->new ( \\@array );\n\nwhile (my @perm = $piterator->next) {\nprint \"next permutation: (@perm)\\n\";\n}\n\nFor even faster execution, you could do:\n\nuse Algorithm::Permute;\n\nmy @array = 'a'..'d';\n\nAlgorithm::Permute::permute {\nprint \"next permutation: (@array)\\n\";\n} @array;\n\nHere's a little program that generates all permutations of all the words\non each line of input. The algorithm embodied in the permute() function\nis discussed in Volume 4 (still unpublished) of Knuth's *The Art of\nComputer Programming* and will work on any list:\n\n#!/usr/bin/perl -n\n# Fischer-Krause ordered permutation generator\n\nsub permute (&@) {\nmy $code = shift;\nmy @idx = 0..$#;\nwhile ( $code->(@[@idx]) ) {\nmy $p = $#idx;\n--$p while $idx[$p-1] > $idx[$p];\nmy $q = $p or return;\npush @idx, reverse splice @idx, $p;\n++$q while $idx[$p-1] > $idx[$q];\n@idx[$p-1,$q]=@idx[$q,$p-1];\n}\n}\n\npermute { print \"@\\n\" } split;\n\nThe Algorithm::Loops module also provides the \"NextPermute\" and\n\"NextPermuteNum\" functions which efficiently find all unique\npermutations of an array, even if it contains duplicate values,\nmodifying it in-place: if its elements are in reverse-sorted order then\nthe array is reversed, making it sorted, and it returns false; otherwise\nthe next permutation is returned.\n\n\"NextPermute\" uses string order and \"NextPermuteNum\" numeric order, so\nyou can enumerate all the permutations of 0..9 like this:\n\nuse Algorithm::Loops qw(NextPermuteNum);\n\nmy @list= 0..9;\ndo { print \"@list\\n\" } while NextPermuteNum @list;\n\nHow do I sort a hash (optionally by value instead of key)?\n(contributed by brian d foy)\n\nTo sort a hash, start with the keys. In this example, we give the list\nof keys to the sort function which then compares them ASCIIbetically\n(which might be affected by your locale settings). The output list has\nthe keys in ASCIIbetical order. Once we have the keys, we can go through\nthem to create a report which lists the keys in ASCIIbetical order.\n\nmy @keys = sort { $a cmp $b } keys %hash;\n\nforeach my $key ( @keys ) {\nprintf \"%-20s %6d\\n\", $key, $hash{$key};\n}\n\nWe could get more fancy in the sort() block though. Instead of comparing\nthe keys, we can compute a value with them and use that value as the\ncomparison.\n\nFor instance, to make our report order case-insensitive, we use \"lc\" to\nlowercase the keys before comparing them:\n\nmy @keys = sort { lc $a cmp lc $b } keys %hash;\n\nNote: if the computation is expensive or the hash has many elements, you\nmay want to look at the Schwartzian Transform to cache the computation\nresults.\n\nIf we want to sort by the hash value instead, we use the hash key to\nlook it up. We still get out a list of keys, but this time they are\nordered by their value.\n\nmy @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;\n\nFrom there we can get more complex. If the hash values are the same, we\ncan provide a secondary sort on the hash key.\n\nmy @keys = sort {\n$hash{$a} <=> $hash{$b}\nor\n\"\\L$a\" cmp \"\\L$b\"\n} keys %hash;\n\nWhy don't my tied hashes make the defined/exists distinction?\nThis depends on the tied hash's implementation of EXISTS(). For example,\nthere isn't the concept of undef with hashes that are tied to DBM*\nfiles. It also means that exists() and defined() do the same thing with\na DBM* file, and what they end up doing is not what they do with\nordinary hashes.\n\nHow can I 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 the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?\nUsually a hash ref, perhaps like this:\n\n$record = {\nNAME   => \"Jason\",\nEMPNO  => 132,\nTITLE  => \"deputy peon\",\nAGE    => 23,\nSALARY => 37000,\nPALS   => [ \"Norbert\", \"Rhys\", \"Phineas\"],\n};\n\nReferences are documented in perlref and perlreftut. Examples of complex\ndata structures are given in perldsc and perllol. Examples of structures\nand object-oriented classes are in perlootut.\n\nHow can I check if a key exists in a multilevel hash?\n(contributed by brian d foy)\n\nThe trick to this problem is avoiding accidental autovivification. If\nyou want to check three keys deep, you might naïvely try this:\n\nmy %hash;\nif( exists $hash{key1}{key2}{key3} ) {\n...;\n}\n\nEven though you started with a completely empty hash, after that call to\n\"exists\" you've created the structure you needed to check for \"key3\":\n\n%hash = (\n'key1' => {\n'key2' => {}\n}\n);\n\nThat's autovivification. You can get around this in a few ways. The\neasiest way is to just turn it off. The lexical \"autovivification\"\npragma is available on CPAN. Now you don't add to the hash:\n\n{\nno autovivification;\nmy %hash;\nif( exists $hash{key1}{key2}{key3} ) {\n...;\n}\n}\n\nThe Data::Diver module on CPAN can do it for you too. Its \"Dive\"\nsubroutine can tell you not only if the keys exist but also get the\nvalue:\n\nuse Data::Diver qw(Dive);\n\nmy @exists = Dive( \\%hash, qw(key1 key2 key3) );\nif(  ! @exists  ) {\n...; # keys do not exist\n}\nelsif(  ! defined $exists[0]  ) {\n...; # keys exist but value is undef\n}\n\nYou can easily do this yourself too by checking each level of the hash\nbefore you move onto the next level. This is essentially what\nData::Diver does for you:\n\nif( checkhash( \\%hash, qw(key1 key2 key3) ) ) {\n...;\n}\n\nsub checkhash {\nmy( $hash, @keys ) = @;\n\nreturn unless @keys;\n\nforeach my $key ( @keys ) {\nreturn unless eval { exists $hash->{$key} };\n$hash = $hash->{$key};\n}\n\nreturn 1;\n}\n\nHow do I keep persistent data across program calls?\nFor some specific applications, you can use one of the DBM modules. See\nAnyDBMFile. More generically, you should consult the FreezeThaw or\nStorable modules from CPAN. Starting from Perl 5.8, Storable is part of\nthe standard distribution. Here's one example using Storable's \"store\"\nand \"retrieve\" functions:\n\nuse Storable;\nstore(\\%hash, \"filename\");\n\n# later on...\n$href = retrieve(\"filename\");        # by ref\n%hash = %{ retrieve(\"filename\") };   # direct to hash\n\nHow do I print out or copy a recursive data structure?\nThe Data::Dumper module on CPAN (or the 5.005 release of Perl) is great\nfor printing out data structures. The Storable module on CPAN (or the\n5.8 release of Perl), provides a function called \"dclone\" that\nrecursively copies its argument.\n\nuse Storable qw(dclone);\n$r2 = dclone($r1);\n\nWhere $r1 can be a reference to any kind of data structure you'd like.\nIt will be deeply copied. Because \"dclone\" takes and returns references,\nyou'd have to add extra punctuation if you had a hash of arrays that you\nwanted to copy.\n\n%newhash = %{ dclone(\\%oldhash) };\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq5.pod": {
            "content": "How do I flush/unbuffer an output filehandle? Why must I do this?\n(contributed by brian d foy)\n\nYou might like to read Mark Jason Dominus's \"Suffering From Buffering\"\nat <http://perl.plover.com/FAQs/Buffering.html> .\n\nPerl normally buffers output so it doesn't make a system call for every\nbit of output. By saving up output, it makes fewer expensive system\ncalls. For instance, in this little bit of code, you want to print a dot\nto the screen for every line you process to watch the progress of your\nprogram. Instead of seeing a dot for every line, Perl buffers the output\nand you have a long wait before you see a row of 50 dots all at once:\n\n# long wait, then row of dots all at once\nwhile( <> ) {\nprint \".\";\nprint \"\\n\" unless ++$count % 50;\n\n#... expensive line processing operations\n}\n\nTo get around this, you have to unbuffer the output filehandle, in this\ncase, \"STDOUT\". You can set the special variable $| to a true value\n(mnemonic: making your filehandles \"piping hot\"):\n\n$|++;\n\n# dot shown immediately\nwhile( <> ) {\nprint \".\";\nprint \"\\n\" unless ++$count % 50;\n\n#... expensive line processing operations\n}\n\nThe $| is one of the per-filehandle special variables, so each\nfilehandle has its own copy of its value. If you want to merge standard\noutput and standard error for instance, you have to unbuffer each\n(although STDERR might be unbuffered by default):\n\n{\nmy $previousdefault = select(STDOUT);  # save previous default\n$|++;                                   # autoflush STDOUT\nselect(STDERR);\n$|++;                                   # autoflush STDERR, to be sure\nselect($previousdefault);              # restore previous default\n}\n\n# now should alternate . and +\nwhile( 1 ) {\nsleep 1;\nprint STDOUT \".\";\nprint STDERR \"+\";\nprint STDOUT \"\\n\" unless ++$count % 25;\n}\n\nBesides the $| special variable, you can use \"binmode\" to give your\nfilehandle a \":unix\" layer, which is unbuffered:\n\nbinmode( STDOUT, \":unix\" );\n\nwhile( 1 ) {\nsleep 1;\nprint \".\";\nprint \"\\n\" unless ++$count % 50;\n}\n\nFor more information on output layers, see the entries for \"binmode\" and\nopen in perlfunc, and the PerlIO module documentation.\n\nIf you are using IO::Handle or one of its subclasses, you can call the\n\"autoflush\" method to change the settings of the filehandle:\n\nuse IO::Handle;\nopen my( $iofh ), \">\", \"output.txt\";\n$iofh->autoflush(1);\n\nThe IO::Handle objects also have a \"flush\" method. You can flush the\nbuffer any time you want without auto-buffering\n\n$iofh->flush;\n\nHow do I delete the last N lines from a file?\n(contributed by brian d foy)\n\nThe easiest conceptual solution is to count the lines in the file then\nstart at the beginning and print the number of lines (minus the last N)\nto a new file.\n\nMost often, the real question is how you can delete the last N lines\nwithout making more than one pass over the file, or how to do it without\na lot of copying. The easy concept is the hard reality when you might\nhave millions of lines in your file.\n\nOne trick is to use File::ReadBackwards, which starts at the end of the\nfile. That module provides an object that wraps the real filehandle to\nmake it easy for you to move around the file. Once you get to the spot\nyou need, you can get the actual filehandle and work with it as normal.\nIn this case, you get the file position at the end of the last line you\nwant to keep and truncate the file to that point:\n\nuse File::ReadBackwards;\n\nmy $filename = 'test.txt';\nmy $Linestotruncate = 2;\n\nmy $bw = File::ReadBackwards->new( $filename )\nor die \"Could not read backwards in [$filename]: $!\";\n\nmy $linesfromend = 0;\nuntil( $bw->eof or $linesfromend == $Linestotruncate ) {\nprint \"Got: \", $bw->readline;\n$linesfromend++;\n}\n\ntruncate( $filename, $bw->tell );\n\nThe File::ReadBackwards module also has the advantage of setting the\ninput record separator to a regular expression.\n\nYou can also use the Tie::File module which lets you access the lines\nthrough a tied array. You can use normal array operations to modify your\nfile, including setting the last index and using \"splice\".\n\nHow can I open a filehandle to a string?\n(contributed by Peter J. Holzer, hjp-usenet2@hjp.at)\n\nSince Perl 5.8.0 a file handle referring to a string can be created by\ncalling open with a reference to that string instead of the filename.\nThis file handle can then be used to read from or write to the string:\n\nopen(my $fh, '>', \\$string) or die \"Could not open string for writing\";\nprint $fh \"foo\\n\";\nprint $fh \"bar\\n\";    # $string now contains \"foo\\nbar\\n\"\n\nopen(my $fh, '<', \\$string) or die \"Could not open string for reading\";\nmy $x = <$fh>;    # $x now contains \"foo\\n\"\n\nWith older versions of Perl, the IO::String module provides similar\nfunctionality.\n\nHow can I 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\nWhy do I sometimes get an \"Argument list too long\" when I use <*>?\nThe \"<>\" operator performs a globbing operation (see above). In Perl\nversions earlier than v5.6.0, the internal glob() operator forks csh(1)\nto do the actual glob expansion, but csh can't handle more than 127\nitems and so gives the error message \"Argument list too long\". People\nwho installed tcsh as csh won't have this problem, but their users may\nbe surprised by it.\n\nTo get around this, either upgrade to Perl v5.6.0 or later, do the glob\nyourself with readdir() and patterns, or use a module like File::Glob,\none that doesn't use the shell to do globbing.\n\nWhy can't I just open(FH, \">file.lock\")?\nA common bit of code NOT TO USE is this:\n\nsleep(3) while -e 'file.lock';    # PLEASE DO NOT USE\nopen my $lock, '>', 'file.lock'; # THIS BROKEN CODE\n\nThis is a classic race condition: you take two steps to do something\nwhich must be done in one. That's why computer hardware provides an\natomic test-and-set instruction. In theory, this \"ought\" to work:\n\nsysopen my $fh, \"file.lock\", OWRONLY|OEXCL|OCREAT\nor die \"can't open  file.lock: $!\";\n\nexcept that lamentably, file creation (and deletion) is not atomic over\nNFS, so this won't work (at least, not every time) over the net. Various\nschemes involving link() have been suggested, but these tend to involve\nbusy-wait, which is also less than desirable.\n\nI still don't get locking. I just want to increment the number in the file. How can I do this?\nDidn't anyone ever tell you web-page hit counters were useless? They\ndon't count number of hits, they're a waste of time, and they serve only\nto stroke the writer's vanity. It's better to pick a random number;\nthey're more realistic.\n\nAnyway, this is what you can do if you can't help yourself.\n\nuse Fcntl qw(:DEFAULT :flock);\nsysopen my $fh, \"numfile\", ORDWR|OCREAT or die \"can't open numfile: $!\";\nflock $fh, LOCKEX                        or die \"can't flock numfile: $!\";\nmy $num = <$fh> || 0;\nseek $fh, 0, 0                            or die \"can't rewind numfile: $!\";\ntruncate $fh, 0                           or die \"can't truncate numfile: $!\";\n(print $fh $num+1, \"\\n\")                  or die \"can't write numfile: $!\";\nclose $fh                                 or die \"can't close numfile: $!\";\n\nHere's a much better web-page hit counter:\n\n$hits = int( (time() - 850000000) / rand(1000) );\n\nIf the count doesn't impress your friends, then the code might. :-)\n\nAll I want to do is append a small amount of text to the end of a file. Do I still have to use locking?\nIf you are on a system that correctly implements \"flock\" and you use the\nexample appending code from \"perldoc -f flock\" everything will be OK\neven if the OS you are on doesn't implement append mode correctly (if\nsuch a system exists). So if you are happy to restrict yourself to OSs\nthat implement \"flock\" (and that's not really much of a restriction)\nthen that is what you should do.\n\nIf you know you are only going to use a system that does correctly\nimplement appending (i.e. not Win32) then you can omit the \"seek\" from\nthe code in the previous answer.\n\nIf you know you are only writing code to run on an OS and filesystem\nthat does implement append mode correctly (a local filesystem on a\nmodern Unix for example), and you keep the file in block-buffered mode\nand you write less than one buffer-full of output between each manual\nflushing of the buffer then each bufferload is almost guaranteed to be\nwritten to the end of the file in one chunk without getting intermingled\nwith anyone else's output. You can also use the \"syswrite\" function\nwhich is simply a wrapper around your system's write(2) system call.\n\nThere is still a small theoretical chance that a signal will interrupt\nthe system-level write() operation before completion. There is also a\npossibility that some STDIO implementations may call multiple system\nlevel write()s even if the buffer was empty to start. There may be some\nsystems where this probability is reduced to zero, and this is not a\nconcern when using \":perlio\" instead of your system's STDIO.\n\nHow do I get a file's timestamp in perl?\nIf you want to retrieve the time at which the file was last read,\nwritten, or had its meta-data (owner, etc) changed, you use the -A, -M,\nor -C file test operations as documented in perlfunc. These retrieve the\nage of the file (measured against the start-time of your program) in\ndays as a floating point number. Some platforms may not have all of\nthese times. See perlport for details. To retrieve the \"raw\" time in\nseconds since the epoch, you would call the stat function, then use",
            "subsections": [
                {
                    "name": "localtime",
                    "content": "human-readable form.\n\nHere's an example:\n\nmy $writesecs = (stat($file))[9];\nprintf \"file %s updated at %s\\n\", $file,\nscalar localtime($writesecs);\n\nIf you prefer something more legible, use the File::stat module (part of\nthe standard distribution in version 5.004 and later):\n\n# error checking left as an exercise for reader.\nuse File::stat;\nuse Time::localtime;\nmy $datestring = ctime(stat($file)->mtime);\nprint \"file $file updated at $datestring\\n\";\n\nThe POSIX::strftime() approach has the benefit of being, in theory,\nindependent of the current locale. See perllocale for details.\n\nHow do I set a file's timestamp in perl?\nYou use the utime() function documented in \"utime\" in perlfunc. By way\nof example, here's a little program that copies the read and write times\nfrom its first argument to all the rest of them.\n\nif (@ARGV < 2) {\ndie \"usage: cptimes timestampfile otherfiles ...\\n\";\n}\nmy $timestamp = shift;\nmy($atime, $mtime) = (stat($timestamp))[8,9];\nutime $atime, $mtime, @ARGV;\n\nError checking is, as usual, left as an exercise for the reader.\n\nThe perldoc for utime also has an example that has the same effect as"
                },
                {
                    "name": "touch",
                    "content": "Certain file systems have a limited ability to store the times on a file\nat the expected level of precision. For example, the FAT and HPFS\nfilesystem are unable to create dates on files with a finer granularity\nthan two seconds. This is a limitation of the filesystems, not of"
                },
                {
                    "name": "utime",
                    "content": ""
                }
            ]
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq6.pod": {
            "content": "How 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\nHow do I substitute case-insensitively on the LHS while preserving case on the RHS?\nHere's a lovely Perlish solution by Larry Rosler. It exploits properties\nof bitwise xor on ASCII strings.\n\n$= \"this is a TEsT case\";\n\n$old = 'test';\n$new = 'success';\n\ns{(\\Q$old\\E)}\n{ uc $new | (uc $1 ^ $1) .\n(uc(substr $1, -1) ^ substr $1, -1) x\n(length($new) - length $1)\n}egi;\n\nprint;\n\nAnd here it is as a subroutine, modeled after the above:\n\nsub preservecase {\nmy ($old, $new) = @;\nmy $mask = uc $old ^ $old;\n\nuc $new | $mask .\nsubstr($mask, -1) x (length($new) - length($old))\n}\n\n$string = \"this is a TEsT case\";\n$string =~ s/(test)/preservecase($1, \"success\")/egi;\nprint \"$string\\n\";\n\nThis prints:\n\nthis is a SUcCESS case\n\nAs an alternative, to keep the case of the replacement word if it is\nlonger than the original, you can use this code, by Jeff Pinyan:\n\nsub preservecase {\nmy ($from, $to) = @;\nmy ($lf, $lt) = map length, @;\n\nif ($lt < $lf) { $from = substr $from, 0, $lt }\nelse { $from .= substr $to, $lf }\n\nreturn uc $to | ($from ^ uc $from);\n}\n\nThis changes the sentence to \"this is a SUcCess case.\"\n\nJust to show that C programmers can write C in any programming language,\nif you prefer a more C-like solution, the following script makes the\nsubstitution have the same case, letter by letter, as the original. (It\nalso happens to run about 240% slower than the Perlish solution runs.)\nIf the substitution has more characters than the string being\nsubstituted, the case of the last character is used for the rest of the\nsubstitution.\n\n# Original by Nathan Torkington, massaged by Jeffrey Friedl\n#\nsub preservecase\n{\nmy ($old, $new) = @;\nmy $state = 0; # 0 = no change; 1 = lc; 2 = uc\nmy ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));\nmy $len = $oldlen < $newlen ? $oldlen : $newlen;\n\nfor ($i = 0; $i < $len; $i++) {\nif ($c = substr($old, $i, 1), $c =~ /[\\W\\d]/) {\n$state = 0;\n} elsif (lc $c eq $c) {\nsubstr($new, $i, 1) = lc(substr($new, $i, 1));\n$state = 1;\n} else {\nsubstr($new, $i, 1) = uc(substr($new, $i, 1));\n$state = 2;\n}\n}\n# finish up with any remaining new (for when new is longer than old)\nif ($newlen > $oldlen) {\nif ($state == 1) {\nsubstr($new, $oldlen) = lc(substr($new, $oldlen));\n} elsif ($state == 2) {\nsubstr($new, $oldlen) = uc(substr($new, $oldlen));\n}\n}\nreturn $new;\n}\n\nHow do I use a regular expression to strip C-style comments from a file?\nWhile this actually can be done, it's much harder than you'd think. For\nexample, this one-liner\n\nperl -0777 -pe 's{/\\*.*?\\*/}{}gs' foo.c\n\nwill work in many but not all cases. You see, it's too simple-minded for\ncertain kinds of C programs, in particular, those with what appear to be\ncomments in quoted strings. For that, you'd need something like this,\ncreated by Jeffrey Friedl and later modified by Fred Curtis.\n\n$/ = undef;\n$ = <>;\ns#/\\*[^*]*\\*+([^/*][^*]*\\*+)*/|(\"(\\\\.|[^\"\\\\])*\"|'(\\\\.|[^'\\\\])*'|.[^/\"'\\\\]*)#defined $2 ? $2 : \"\"#gse;\nprint;\n\nThis could, of course, be more legibly written with the \"/x\" modifier,\nadding whitespace and comments. Here it is expanded, courtesy of Fred\nCurtis.\n\ns{\n/\\*         ##  Start of /* ... */ comment\n[^*]*\\*+    ##  Non-* followed by 1-or-more *'s\n(\n[^/*][^*]*\\*+\n)*          ##  0-or-more things which don't start with /\n##    but do end with '*'\n/           ##  End of /* ... */ comment\n\n|         ##     OR  various things which aren't comments:\n\n(\n\"           ##  Start of \" ... \" string\n(\n\\\\.           ##  Escaped char\n|               ##    OR\n[^\"\\\\]        ##  Non \"\\\n)*\n\"           ##  End of \" ... \" string\n\n|         ##     OR\n\n'           ##  Start of ' ... ' string\n(\n\\\\.           ##  Escaped char\n|               ##    OR\n[^'\\\\]        ##  Non '\\\n)*\n'           ##  End of ' ... ' string\n\n|         ##     OR\n\n.           ##  Anything other char\n[^/\"'\\\\]*   ##  Chars which doesn't start a comment, string or escape\n)\n}{defined $2 ? $2 : \"\"}gxse;\n\nA slight modification also removes C++ comments, possibly spanning\nmultiple lines using a continuation character:\n\ns#/\\*[^*]*\\*+([^/*][^*]*\\*+)*/|//([^\\\\]|[^\\n][\\n]?)*?\\n|(\"(\\\\.|[^\"\\\\])*\"|'(\\\\.|[^'\\\\])*'|.[^/\"'\\\\]*)#defined $3 ? $3 : \"\"#gse;\n\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": "Do I always/never have to quote my strings or use semicolons and commas?\nNormally, a bareword doesn't need to be quoted, but in most cases\nprobably should be (and must be under \"use strict\"). But a hash key\nconsisting of a simple word and the left-hand operand to the \"=>\"\noperator both count as though they were quoted:\n\nThis                    is like this\n------------            ---------------\n$foo{line}              $foo{'line'}\nbar => stuff            'bar' => stuff\n\nThe final semicolon in a block is optional, as is the final comma in a\nlist. Good style (see perlstyle) says to put them in except for\none-liners:\n\nif ($whoops) { exit 1 }\nmy @nums = (1, 2, 3);\n\nif ($whoops) {\nexit 1;\n}\n\nmy @lines = (\n\"There Beren came from mountains cold\",\n\"And lost he wandered under leaves\",\n);\n\nHow do I 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 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()?",
            "subsections": [
                {
                    "name": "local",
                    "content": "a new value for the duration of the subroutine *which is visible in\nother functions called from that subroutine*. This is done at run-time,\nso is called dynamic scoping. local() always affects global variables,\nalso called package variables or dynamic variables.\n"
                },
                {
                    "name": "my",
                    "content": "subroutine. This is done at compile-time, so it is called lexical or\nstatic scoping. my() always affects private variables, also called\nlexical variables or (improperly) static(ly scoped) variables.\n\nFor instance:\n\nsub visible {\nprint \"var has value $var\\n\";\n}\n\nsub dynamic {\nlocal $var = 'local';    # new temporary value for the still-global\nvisible();              #   variable called $var\n}\n\nsub lexical {\nmy $var = 'private';    # new private variable, $var\nvisible();              # (invisible outside of sub scope)\n}\n\n$var = 'global';\n\nvisible();              # prints global\ndynamic();              # prints local\nlexical();              # prints global\n\nNotice how at no point does the value \"private\" get printed. That's\nbecause $var only has that value within the block of the lexical()\nfunction, and it is hidden from the called subroutine.\n\nIn summary, local() doesn't make what you think of as private, local\nvariables. It gives a global variable a temporary value. my() is what\nyou're looking for if you want private variables.\n\nSee \"Private Variables via my()\" in perlsub and \"Temporary Values via"
                },
                {
                    "name": "local",
                    "content": "How 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"
                }
            ]
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq8.pod": {
            "content": "How do I find out which operating system I'm running under?\nThe $^O variable ($OSNAME if you use \"English\") contains an indication\nof the name of the operating system (not its release number) that your\nperl binary was built for.\n\nHow do I do fancy stuff with the keyboard/screen/mouse?\nHow you access/control keyboards, screens, and pointing devices (\"mice\")\nis system-dependent. Try the following modules:\n\nKeyboard\nTerm::Cap               Standard perl distribution\nTerm::ReadKey           CPAN\nTerm::ReadLine::Gnu     CPAN\nTerm::ReadLine::Perl    CPAN\nTerm::Screen            CPAN\n\nScreen\nTerm::Cap               Standard perl distribution\nCurses                  CPAN\nTerm::ANSIColor         CPAN\n\nMouse\nTk                      CPAN\nWx                      CPAN\nGtk2                    CPAN\nQt4                     kdebindings4 package\n\nSome of these specific cases are shown as examples in other answers in\nthis section of the perlfaq.\n\nHow do I read just one key without waiting for a return key?\nControlling input buffering is a remarkably system-dependent matter. On\nmany systems, you can just use the stty command as shown in \"getc\" in\nperlfunc, but as you see, that's already getting you into portability\nsnags.\n\nopen(TTY, \"+</dev/tty\") or die \"no tty: $!\";\nsystem \"stty  cbreak </dev/tty >/dev/tty 2>&1\";\n$key = getc(TTY);        # perhaps this works\n# OR ELSE\nsysread(TTY, $key, 1);    # probably this does\nsystem \"stty -cbreak </dev/tty >/dev/tty 2>&1\";\n\nThe Term::ReadKey module from CPAN offers an easy-to-use interface that\nshould be more efficient than shelling out to stty for each key. It even\nincludes limited support for Windows.\n\nuse Term::ReadKey;\nReadMode('cbreak');\n$key = ReadKey(0);\nReadMode('normal');\n\nHowever, using the code requires that you have a working C compiler and\ncan use it to build and install a CPAN module. Here's a solution using\nthe standard POSIX module, which is already on your system (assuming\nyour system supports POSIX).\n\nuse HotKey;\n$key = readkey();\n\nAnd here's the \"HotKey\" module, which hides the somewhat mystifying\ncalls to manipulate the POSIX termios structures.\n\n# HotKey.pm\npackage HotKey;\n\nuse strict;\nuse warnings;\n\nuse parent 'Exporter';\nour @EXPORT = qw(cbreak cooked readkey);\n\nuse POSIX qw(:termiosh);\nmy ($term, $oterm, $echo, $noecho, $fdstdin);\n\n$fdstdin = fileno(STDIN);\n$term     = POSIX::Termios->new();\n$term->getattr($fdstdin);\n$oterm     = $term->getlflag();\n\n$echo     = ECHO | ECHOK | ICANON;\n$noecho   = $oterm & ~$echo;\n\nsub cbreak {\n$term->setlflag($noecho);  # ok, so i don't want echo either\n$term->setcc(VTIME, 1);\n$term->setattr($fdstdin, TCSANOW);\n}\n\nsub cooked {\n$term->setlflag($oterm);\n$term->setcc(VTIME, 0);\n$term->setattr($fdstdin, TCSANOW);\n}\n\nsub readkey {\nmy $key = '';\ncbreak();\nsysread(STDIN, $key, 1);\ncooked();\nreturn $key;\n}\n\nEND { cooked() }\n\n1;\n\nHow do I start a process in the background?\n(contributed by brian d foy)\n\nThere's not a single way to run code in the background so you don't have\nto wait for it to finish before your program moves on to other tasks.\nProcess management depends on your particular operating system, and many\nof the techniques are covered in perlipc.\n\nSeveral CPAN modules may be able to help, including IPC::Open2 or\nIPC::Open3, IPC::Run, Parallel::Jobs, Parallel::ForkManager, POE,\nProc::Background, and Win32::Process. There are many other modules you\nmight use, so check those namespaces for other options too.\n\nIf you are on a Unix-like system, you might be able to get away with a\nsystem call where you put an \"&\" on the end of the command:\n\nsystem(\"cmd &\")\n\nYou can also try using \"fork\", as described in perlfunc (although this\nis the same thing that many of the modules will do for you).\n\nSTDIN, STDOUT, and STDERR are shared\nBoth the main process and the backgrounded one (the \"child\" process)\nshare the same STDIN, STDOUT and STDERR filehandles. If both try to\naccess them at once, strange things can happen. You may want to\nclose or reopen these for the child. You can get around this with\n\"open\"ing a pipe (see \"open\" in perlfunc) but on some systems this\nmeans that the child process cannot outlive the parent.\n\nSignals\nYou'll have to catch the SIGCHLD signal, and possibly SIGPIPE too.\nSIGCHLD is sent when the backgrounded process finishes. SIGPIPE is\nsent when you write to a filehandle whose child process has closed\n(an untrapped SIGPIPE can cause your program to silently die). This\nis not an issue with system(\"cmd&\").\n\nZombies\nYou have to be prepared to \"reap\" the child process when it\nfinishes.\n\n$SIG{CHLD} = sub { wait };\n\n$SIG{CHLD} = 'IGNORE';\n\nYou can also use a double fork. You immediately wait() for your\nfirst child, and the init daemon will wait() for your grandchild\nonce it exits.\n\nunless ($pid = fork) {\nunless (fork) {\nexec \"what you really wanna do\";\ndie \"exec failed!\";\n}\nexit 0;\n}\nwaitpid($pid, 0);\n\nSee \"Signals\" in perlipc for other examples of code to do this.\nZombies are not an issue with \"system(\"prog &\")\".\n\nHow do I modify the shadow password file on a Unix system?\nIf perl was installed correctly and your shadow library was written\nproperly, the \"getpw*()\" functions described in perlfunc should in\ntheory provide (read-only) access to entries in the shadow password\nfile. To change the file, make a new shadow password file (the format\nvaries from system to system--see passwd(1) for specifics) and use",
            "subsections": [
                {
                    "name": "pwd_mkdb",
                    "content": "Why doesn't my sockets program work under System V (Solaris)? What does the error message \"Protocol not supported\" mean?\nSome Sys-V based systems, notably Solaris 2.X, redefined some of the\nstandard socket constants. Since these were constant across all\narchitectures, they were often hardwired into perl code. The proper way\nto deal with this is to \"use Socket\" to get the correct values.\n\nNote that even though SunOS and Solaris are binary compatible, these\nvalues are different. Go figure.\n\nHow can I call my system's unique C functions from Perl?\nIn most cases, you write an external module to do it--see the answer to\n\"Where can I learn about linking C with Perl? [h2xs, xsubpp]\". However,\nif the function is a system call, and your system supports syscall(),\nyou can use the \"syscall\" function (documented in perlfunc).\n\nRemember to check the modules that came with your distribution, and CPAN\nas well--someone may already have written a module to do it. On Windows,\ntry Win32::API. On Macs, try Mac::Carbon. If no module has an interface\nto the C function, you can inline a bit of C in your Perl source with\nInline::C.\n\nWhy can't I get the output of a command with system()?\nYou're confusing the purpose of system() and backticks (``). system()\nruns a command and returns exit status information (as a 16 bit value:\nthe low 7 bits are the signal the process died from, if any, and the\nhigh 8 bits are the actual exit value). Backticks (``) run a command and\nreturn what it sent to STDOUT.\n\nmy $exitstatus   = system(\"mail-users\");\nmy $outputstring = `ls`;\n\nHow can I capture STDERR from an external command?\nThere are three basic ways of running external commands:\n\nsystem $cmd;        # using system()\nmy $output = `$cmd`;        # using backticks (``)\nopen (my $pipefh, \"$cmd |\");    # using open()\n\nWith system(), both STDOUT and STDERR will go the same place as the\nscript's STDOUT and STDERR, unless the system() command redirects them.\nBackticks and open() read only the STDOUT of your command.\n\nYou can also use the open3() function from IPC::Open3. Benjamin Goldberg\nprovides some sample code:\n\nTo capture a program's STDOUT, but discard its STDERR:\n\nuse IPC::Open3;\nuse File::Spec;\nmy $in = '';\nopen(NULL, \">\", File::Spec->devnull);\nmy $pid = open3($in, \\*PH, \">&NULL\", \"cmd\");\nwhile( <PH> ) { }\nwaitpid($pid, 0);\n\nTo capture a program's STDERR, but discard its STDOUT:\n\nuse IPC::Open3;\nuse File::Spec;\nmy $in = '';\nopen(NULL, \">\", File::Spec->devnull);\nmy $pid = open3($in, \">&NULL\", \\*PH, \"cmd\");\nwhile( <PH> ) { }\nwaitpid($pid, 0);\n\nTo capture a program's STDERR, and let its STDOUT go to our own STDERR:\n\nuse IPC::Open3;\nmy $in = '';\nmy $pid = open3($in, \">&STDERR\", \\*PH, \"cmd\");\nwhile( <PH> ) { }\nwaitpid($pid, 0);\n\nTo read both a command's STDOUT and its STDERR separately, you can\nredirect them to temp files, let the command run, then read the temp\nfiles:\n\nuse IPC::Open3;\nuse IO::File;\nmy $in = '';\nlocal *CATCHOUT = IO::File->newtmpfile;\nlocal *CATCHERR = IO::File->newtmpfile;\nmy $pid = open3($in, \">&CATCHOUT\", \">&CATCHERR\", \"cmd\");\nwaitpid($pid, 0);\nseek $, 0, 0 for \\*CATCHOUT, \\*CATCHERR;\nwhile( <CATCHOUT> ) {}\nwhile( <CATCHERR> ) {}\n\nBut there's no real need for both to be tempfiles... the following\nshould work just as well, without deadlocking:\n\nuse IPC::Open3;\nmy $in = '';\nuse IO::File;\nlocal *CATCHERR = IO::File->newtmpfile;\nmy $pid = open3($in, \\*CATCHOUT, \">&CATCHERR\", \"cmd\");\nwhile( <CATCHOUT> ) {}\nwaitpid($pid, 0);\nseek CATCHERR, 0, 0;\nwhile( <CATCHERR> ) {}\n\nAnd it'll be faster, too, since we can begin processing the program's\nstdout immediately, rather than waiting for the program to finish.\n\nWith any of these, you can change file descriptors before the call:\n\nopen(STDOUT, \">logfile\");\nsystem(\"ls\");\n\nor you can use Bourne shell file-descriptor redirection:\n\n$output = `$cmd 2>somefile`;\nopen (PIPE, \"cmd 2>somefile |\");\n\nYou can also use file-descriptor redirection to make STDERR a duplicate\nof STDOUT:\n\n$output = `$cmd 2>&1`;\nopen (PIPE, \"cmd 2>&1 |\");\n\nNote that you *cannot* simply open STDERR to be a dup of STDOUT in your\nPerl program and avoid calling the shell to do the redirection. This\ndoesn't work:\n\nopen(STDERR, \">&STDOUT\");\n$alloutput = `cmd args`;  # stderr still escapes\n\nThis fails because the open() makes STDERR go to where STDOUT was going\nat the time of the open(). The backticks then make STDOUT go to a\nstring, but don't change STDERR (which still goes to the old STDOUT).\n\nNote that you *must* use Bourne shell (sh(1)) redirection syntax in\nbackticks, not csh(1)! Details on why Perl's system() and backtick and\npipe opens all use the Bourne shell are in the versus/csh.whynot article\nin the \"Far More Than You Ever Wanted To Know\" collection in\n<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> . To capture a command's\nSTDERR and STDOUT together:\n\n$output = `cmd 2>&1`;                       # either with backticks\n$pid = open(PH, \"cmd 2>&1 |\");              # or with an open pipe\nwhile (<PH>) { }                            #    plus a read\n\nTo capture a command's STDOUT but discard its STDERR:\n\n$output = `cmd 2>/dev/null`;                # either with backticks\n$pid = open(PH, \"cmd 2>/dev/null |\");       # or with an open pipe\nwhile (<PH>) { }                            #    plus a read\n\nTo capture a command's STDERR but discard its STDOUT:\n\n$output = `cmd 2>&1 1>/dev/null`;           # either with backticks\n$pid = open(PH, \"cmd 2>&1 1>/dev/null |\");  # or with an open pipe\nwhile (<PH>) { }                            #    plus a read\n\nTo exchange a command's STDOUT and STDERR in order to capture the STDERR\nbut leave its STDOUT to come out our old STDERR:\n\n$output = `cmd 3>&1 1>&2 2>&3 3>&-`;        # either with backticks\n$pid = open(PH, \"cmd 3>&1 1>&2 2>&3 3>&-|\");# or with an open pipe\nwhile (<PH>) { }                            #    plus a read\n\nTo read both a command's STDOUT and its STDERR separately, it's easiest\nto redirect them separately to files, and then read from those files\nwhen the program is done:\n\nsystem(\"program args 1>program.stdout 2>program.stderr\");\n\nOrdering is important in all these examples. That's because the shell\nprocesses file descriptor redirections in strictly left to right order.\n\nsystem(\"prog args 1>tmpfile 2>&1\");\nsystem(\"prog args 2>&1 1>tmpfile\");\n\nThe first command sends both standard out and standard error to the\ntemporary file. The second command sends only the old standard output\nthere, and the old standard error shows up on the old standard out.\n\nWhy 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 do I avoid zombies on a Unix system?\nUse the reaper code from \"Signals\" in perlipc to call wait() when a\nSIGCHLD is received, or else use the double-fork technique described in\n\"How do I start a process in the background?\" in perlfaq8.\n\nHow do I 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 install a module from CPAN?\n(contributed by brian d foy)\n\nThe easiest way is to have a module also named CPAN do it for you by\nusing the \"cpan\" command that comes with Perl. You can give it a list of\nmodules to install:\n\n$ cpan IO::Interactive Getopt::Whatever\n\nIf you prefer \"CPANPLUS\", it's just as easy:\n\n$ cpanp i IO::Interactive Getopt::Whatever\n\nIf you want to install a distribution from the current directory, you\ncan tell \"CPAN.pm\" to install \".\" (the full stop):\n\n$ cpan .\n\nSee the documentation for either of those commands to see what else you\ncan do.\n\nIf you want to try to install a distribution by yourself, resolving all\ndependencies on your own, you follow one of two possible build paths.\n\nFor distributions that use *Makefile.PL*:\n\n$ perl Makefile.PL\n$ make test install\n\nFor distributions that use *Build.PL*:\n\n$ perl Build.PL\n$ ./Build test\n$ ./Build install\n\nSome distributions may need to link to libraries or other third-party\ncode and their build and installation sequences may be more complicated.\nCheck any *README* or *INSTALL* files that you may find.\n\nWhere are modules installed?\nModules are installed on a case-by-case basis (as provided by the\nmethods described in the previous section), and in the operating system.\nAll of these paths are stored in @INC, which you can display with the\none-liner\n\nperl -e 'print join(\"\\n\",@INC,\"\")'\n\nThe same information is displayed at the end of the output from the\ncommand\n\nperl -V\n\nTo find out where a module's source code is located, use\n\nperldoc -l Encode\n\nto display the path to the module. In some cases (for example, the\n\"AutoLoader\" module), this command will show the path to a separate\n\"pod\" file; the module itself should be in the same directory, with a\n'pm' file extension.\n"
                }
            ]
        },
        "Found in /usr/share/perl/5.38/pod/perlfaq9.pod": {
            "content": "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 a MIME/BASE64 string?\nThe MIME::Base64 package handles this as well as the MIME/QP encoding.\nDecoding base 64 becomes as simple as:\n\nuse MIME::Base64;\nmy $decoded = decodebase64($encoded);\n\nThe Email::MIME module can decode base 64-encoded email message parts\ntransparently so the developer doesn't need to worry about it.\n\nHow do I find 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": []
        }
    },
    "flags": [],
    "examples": [],
    "see_also": []
}