{
    "mode": "man",
    "parameter": "perlfaq4",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/perlfaq4/1/json",
    "generated": "2026-06-15T16:44:03Z",
    "sections": {
        "NAME": {
            "content": "perlfaq4 - Data Manipulation\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 5.20210411\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This section of the FAQ answers questions related to manipulating numbers, dates, strings,\narrays, hashes, and miscellaneous data issues.\n",
            "subsections": [
                {
                    "name": "Data: Numbers",
                    "content": ""
                },
                {
                    "name": "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting",
                    "content": ""
                },
                {
                    "name": "(eg, 19.95)?",
                    "content": "For the long explanation, see David Goldberg's \"What Every Computer Scientist Should Know\nAbout Floating-Point Arithmetic\"\n(<http://web.cse.msu.edu/~cse320/Documents/FloatingPoint.pdf>).\n\nInternally, your computer represents floating-point numbers in binary.  Digital (as in powers\nof two) computers cannot store all numbers exactly. Some real numbers lose precision in the\nprocess. This is a problem with how computers store numbers and affects all computer\nlanguages, not just Perl.\n\nperlnumber shows the gory details of number representations and conversions.\n\nTo limit the number of decimal places in your numbers, you can use the \"printf\" or \"sprintf\"\nfunction. See \"Floating-point Arithmetic\" in perlop for more details.\n\nprintf \"%.2f\", 10/3;\n\nmy $number = sprintf \"%.2f\", 10/3;\n"
                },
                {
                    "name": "Why is int() broken?",
                    "content": "Your \"int()\" is most probably working just fine. It's the numbers that aren't quite what you\nthink.\n\nFirst, see the answer to \"Why am I getting long decimals (eg, 19.9499999999999) instead of\nthe numbers I should be getting (eg, 19.95)?\".\n\nFor example, this\n\nprint int(0.6/0.2-2), \"\\n\";\n\nwill in most computers print 0, not 1, because even such simple numbers as 0.6 and 0.2 cannot\nbe presented exactly by floating-point numbers. What you think in the above as 'three' is\nreally more like 2.9999999999999995559.\n"
                },
                {
                    "name": "Why isn't my octal data interpreted correctly?",
                    "content": "(contributed by brian d foy)\n\nYou're probably trying to convert a string to a number, which Perl only converts as a decimal\nnumber. When Perl converts a string to a number, it ignores leading spaces and zeroes, then\nassumes the rest of the digits are in base 10:\n\nmy $string = '0644';\n\nprint $string + 0;  # prints 644\n\nprint $string + 44; # prints 688, certainly not octal!\n\nThis problem usually involves one of the Perl built-ins that has the same name a Unix command\nthat uses octal numbers as arguments on the command line. In this example, \"chmod\" on the\ncommand line knows that its first argument is octal because that's what it does:\n\n%prompt> chmod 644 file\n\nIf you want to use the same literal digits (644) in Perl, you have to tell Perl to treat them\nas octal numbers either by prefixing the digits with a 0 or using \"oct\":\n\nchmod(     0644, $filename );  # right, has leading zero\nchmod( oct(644), $filename );  # also correct\n\nThe problem comes in when you take your numbers from something that Perl thinks is a string,\nsuch as a command line argument in @ARGV:\n\nchmod( $ARGV[0],      $filename );  # wrong, even if \"0644\"\n\nchmod( oct($ARGV[0]), $filename );  # correct, treat string as octal\n\nYou can always check the value you're using by printing it in octal notation to ensure it\nmatches what you think it should be. Print it in octal  and decimal format:\n\nprintf \"0%o %d\", $number, $number;\n"
                },
                {
                    "name": "Does Perl have a round() function? What about ceil() and floor()? Trig functions?",
                    "content": "Remember that \"int()\" merely truncates toward 0. For rounding to a certain number of digits,\n\"sprintf()\" or \"printf()\" is usually the easiest route.\n\nprintf(\"%.3f\", 3.1415926535);   # prints 3.142\n\nThe POSIX module (part of the standard Perl distribution) implements \"ceil()\", \"floor()\", and\na number of other mathematical and trigonometric functions.\n\nuse POSIX;\nmy $ceil   = ceil(3.5);   # 4\nmy $floor  = floor(3.5);  # 3\n\nIn 5.000 to 5.003 perls, trigonometry was done in the Math::Complex module. With 5.004, the\nMath::Trig module (part of the standard Perl distribution) implements the trigonometric\nfunctions. Internally it uses the Math::Complex module and some functions can break out from\nthe real axis into the complex plane, for example the inverse sine of 2.\n\nRounding in financial applications can have serious implications, and the rounding method\nused should be specified precisely. In these cases, it probably pays not to trust whichever\nsystem of rounding is being used by Perl, but instead to implement the rounding function you\nneed yourself.\n\nTo see why, notice how you'll still have an issue on half-way-point alternation:\n\nfor (my $i = -5; $i <= 5; $i += 0.5) { printf \"%.0f \",$i }\n\n-5 -4 -4 -4 -3 -2 -2 -2 -1 -0 0 0 1 2 2 2 3 4 4 4 5\n\nDon't blame Perl. It's the same as in C. IEEE says we have to do this. Perl numbers whose\nabsolute values are integers under 231 (on 32-bit machines) will work pretty much like\nmathematical integers.  Other numbers are not guaranteed.\n"
                },
                {
                    "name": "How do I convert between numeric representations/bases/radixes?",
                    "content": "As always with Perl there is more than one way to do it. Below are a few examples of\napproaches to making common conversions between number representations. This is intended to\nbe representational rather than exhaustive.\n\nSome of the examples later in perlfaq4 use the Bit::Vector module from CPAN. The reason you\nmight choose Bit::Vector over the perl built-in functions is that it works with numbers of\nANY size, that it is optimized for speed on some operations, and for at least some\nprogrammers the notation might be familiar.\n\nHow do I convert hexadecimal into decimal\nUsing perl's built in conversion of \"0x\" notation:\n\nmy $dec = 0xDEADBEEF;\n\nUsing the \"hex\" function:\n\nmy $dec = hex(\"DEADBEEF\");\n\nUsing \"pack\":\n\nmy $dec = unpack(\"N\", pack(\"H8\", substr(\"0\" x 8 . \"DEADBEEF\", -8)));\n\nUsing the CPAN module \"Bit::Vector\":\n\nuse Bit::Vector;\nmy $vec = Bit::Vector->newHex(32, \"DEADBEEF\");\nmy $dec = $vec->toDec();\n\nHow do I convert from decimal to hexadecimal\nUsing \"sprintf\":\n\nmy $hex = sprintf(\"%X\", 3735928559); # upper case A-F\nmy $hex = sprintf(\"%x\", 3735928559); # lower case a-f\n\nUsing \"unpack\":\n\nmy $hex = unpack(\"H*\", pack(\"N\", 3735928559));\n\nUsing Bit::Vector:\n\nuse Bit::Vector;\nmy $vec = Bit::Vector->newDec(32, -559038737);\nmy $hex = $vec->toHex();\n\nAnd Bit::Vector supports odd bit counts:\n\nuse Bit::Vector;\nmy $vec = Bit::Vector->newDec(33, 3735928559);\n$vec->Resize(32); # suppress leading 0 if unwanted\nmy $hex = $vec->toHex();\n\nHow do I convert from octal to decimal\nUsing Perl's built in conversion of numbers with leading zeros:\n\nmy $dec = 033653337357; # note the leading 0!\n\nUsing the \"oct\" function:\n\nmy $dec = oct(\"33653337357\");\n\nUsing Bit::Vector:\n\nuse Bit::Vector;\nmy $vec = Bit::Vector->new(32);\n$vec->ChunkListStore(3, split(//, reverse \"33653337357\"));\nmy $dec = $vec->toDec();\n\nHow do I convert from decimal to octal\nUsing \"sprintf\":\n\nmy $oct = sprintf(\"%o\", 3735928559);\n\nUsing Bit::Vector:\n\nuse Bit::Vector;\nmy $vec = Bit::Vector->newDec(32, -559038737);\nmy $oct = reverse join('', $vec->ChunkListRead(3));\n\nHow do I convert from binary to decimal\nPerl 5.6 lets you write binary numbers directly with the \"0b\" notation:\n\nmy $number = 0b10110110;\n\nUsing \"oct\":\n\nmy $input = \"10110110\";\nmy $decimal = oct( \"0b$input\" );\n\nUsing \"pack\" and \"ord\":\n\nmy $decimal = ord(pack('B8', '10110110'));\n\nUsing \"pack\" and \"unpack\" for larger strings:\n\nmy $int = unpack(\"N\", pack(\"B32\",\nsubstr(\"0\" x 32 . \"11110101011011011111011101111\", -32)));\nmy $dec = sprintf(\"%d\", $int);\n\n# substr() is used to left-pad a 32-character string with zeros.\n\nUsing Bit::Vector:\n\nmy $vec = Bit::Vector->newBin(32, \"11011110101011011011111011101111\");\nmy $dec = $vec->toDec();\n\nHow do I convert from decimal to binary\nUsing \"sprintf\" (perl 5.6+):\n\nmy $bin = sprintf(\"%b\", 3735928559);\n\nUsing \"unpack\":\n\nmy $bin = unpack(\"B*\", pack(\"N\", 3735928559));\n\nUsing Bit::Vector:\n\nuse Bit::Vector;\nmy $vec = Bit::Vector->newDec(32, -559038737);\nmy $bin = $vec->toBin();\n\nThe remaining transformations (e.g. hex -> oct, bin -> hex, etc.)  are left as an\nexercise to the inclined reader.\n"
                },
                {
                    "name": "Why doesn't & work the way I want it to?",
                    "content": "The behavior of binary arithmetic operators depends on whether they're used on numbers or\nstrings. The operators treat a string as a series of bits and work with that (the string \"3\"\nis the bit pattern 00110011). The operators work with the binary form of a number (the number\n3 is treated as the bit pattern 00000011).\n\nSo, saying \"11 & 3\" performs the \"and\" operation on numbers (yielding 3). Saying \"11\" & \"3\"\nperforms the \"and\" operation on strings (yielding \"1\").\n\nMost problems with \"&\" and \"|\" arise because the programmer thinks they have a number but\nreally it's a string or vice versa. To avoid this, stringify the arguments explicitly (using\n\"\" or \"qq()\") or convert them to numbers explicitly (using \"0+$arg\"). The rest arise because\nthe programmer says:\n\nif (\"\\020\\020\" & \"\\101\\101\") {\n# ...\n}\n\nbut a string consisting of two null bytes (the result of \"\\020\\020\" & \"\\101\\101\") is not a\nfalse value in Perl. You need:\n\nif ( (\"\\020\\020\" & \"\\101\\101\") !~ /[^\\000]/) {\n# ...\n}\n"
                },
                {
                    "name": "How do I multiply matrices?",
                    "content": "Use the Math::Matrix or Math::MatrixReal modules (available from CPAN) or the PDL extension\n(also available from CPAN).\n"
                },
                {
                    "name": "How do I perform an operation on a series of integers?",
                    "content": "To call a function on each element in an array, and collect the results, use:\n\nmy @results = map { myfunc($) } @array;\n\nFor example:\n\nmy @triple = map { 3 * $ } @single;\n\nTo call a function on each element of an array, but ignore the results:\n\nforeach my $iterator (@array) {\nsomefunc($iterator);\n}\n\nTo call a function on each integer in a (small) range, you can use:\n\nmy @results = map { somefunc($) } (5 .. 25);\n\nbut you should be aware that in this form, the \"..\" operator creates a list of all integers\nin the range, which can take a lot of memory for large ranges. However, the problem does not\noccur when using \"..\" within a \"for\" loop, because in that case the range operator is\noptimized to iterate over the range, without creating the entire list. So\n\nmy @results = ();\nfor my $i (5 .. 500005) {\npush(@results, somefunc($i));\n}\n\nor even\n\npush(@results, somefunc($)) for 5 .. 500005;\n\nwill not create an intermediate list of 500,000 integers.\n"
                },
                {
                    "name": "How can I output Roman numerals?",
                    "content": "Get the <http://www.cpan.org/modules/by-module/Roman> module.\n"
                },
                {
                    "name": "Why aren't my random numbers random?",
                    "content": "If you're using a version of Perl before 5.004, you must call \"srand\" once at the start of\nyour program to seed the random number generator.\n\nBEGIN { srand() if $] < 5.004 }\n\n5.004 and later automatically call \"srand\" at the beginning. Don't call \"srand\" more than\nonce--you make your numbers less random, rather than more.\n\nComputers are good at being predictable and bad at being random (despite appearances caused\nby bugs in your programs :-). The random article in the \"Far More Than You Ever Wanted To\nKnow\" collection in <http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz>, courtesy of Tom Phoenix,\ntalks more about this. John von Neumann said, \"Anyone who attempts to generate random numbers\nby deterministic means is, of course, living in a state of sin.\"\n\nPerl relies on the underlying system for the implementation of \"rand\" and \"srand\"; on some\nsystems, the generated numbers are not random enough (especially on Windows : see\n<http://www.perlmonks.org/?nodeid=803632>).  Several CPAN modules in the \"Math\" namespace\nimplement better pseudorandom generators; see for example Math::Random::MT (\"Mersenne\nTwister\", fast), or Math::TrulyRandom (uses the imperfections in the system's timer to\ngenerate random numbers, which is rather slow).  More algorithms for random numbers are\ndescribed in \"Numerical Recipes in C\" at <http://www.nr.com/>\n"
                },
                {
                    "name": "How do I get a random number between X and Y?",
                    "content": "To get a random number between two values, you can use the \"rand()\" built-in to get a random\nnumber between 0 and 1. From there, you shift that into the range that you want.\n\n\"rand($x)\" returns a number such that \"0 <= rand($x) < $x\". Thus what you want to have perl\nfigure out is a random number in the range from 0 to the difference between your X and Y.\n\nThat is, to get a number between 10 and 15, inclusive, you want a random number between 0 and\n5 that you can then add to 10.\n\nmy $number = 10 + int rand( 15-10+1 ); # ( 10,11,12,13,14, or 15 )\n\nHence you derive the following simple function to abstract that. It selects a random integer\nbetween the two given integers (inclusive). For example: \"randomintbetween(50,120)\".\n\nsub randomintbetween {\nmy($min, $max) = @;\n# Assumes that the two arguments are integers themselves!\nreturn $min if $min == $max;\n($min, $max) = ($max, $min)  if  $min > $max;\nreturn $min + int rand(1 + $max - $min);\n}\n"
                },
                {
                    "name": "Data: Dates",
                    "content": ""
                },
                {
                    "name": "How do I find the day or week of the year?",
                    "content": "The day of the year is in the list returned by the \"localtime\" function. Without an argument\n\"localtime\" uses the current time.\n\nmy $dayofyear = (localtime)[7];\n\nThe POSIX module can also format a date as the day of the year or week of the year.\n\nuse POSIX qw/strftime/;\nmy $dayofyear  = strftime \"%j\", localtime;\nmy $weekofyear = strftime \"%W\", localtime;\n\nTo get the day of year for any date, use POSIX's \"mktime\" to get a time in epoch seconds for\nthe argument to \"localtime\".\n\nuse POSIX qw/mktime strftime/;\nmy $weekofyear = strftime \"%W\",\nlocaltime( mktime( 0, 0, 0, 18, 11, 87 ) );\n\nYou can also use Time::Piece, which comes with Perl and provides a \"localtime\" that returns\nan object:\n\nuse Time::Piece;\nmy $dayofyear  = localtime->yday;\nmy $weekofyear = localtime->week;\n\nThe Date::Calc module provides two functions to calculate these, too:\n\nuse Date::Calc;\nmy $dayofyear  = DayofYear(  1987, 12, 18 );\nmy $weekofyear = WeekofYear( 1987, 12, 18 );\n"
                },
                {
                    "name": "How do I find the current century or millennium?",
                    "content": "Use the following simple functions:\n\nsub getcentury    {\nreturn int((((localtime(shift || time))[5] + 1999))/100);\n}\n\nsub getmillennium {\nreturn 1+int((((localtime(shift || time))[5] + 1899))/1000);\n}\n\nOn some systems, the POSIX module's \"strftime()\" function has been extended in a non-standard\nway to use a %C format, which they sometimes claim is the \"century\". It isn't, because on\nmost such systems, this is only the first two digits of the four-digit year, and thus cannot\nbe used to determine reliably the current century or millennium.\n"
                },
                {
                    "name": "How can I compare two dates and find the difference?",
                    "content": "(contributed by brian d foy)\n\nYou could just store all your dates as a number and then subtract.  Life isn't always that\nsimple though.\n\nThe Time::Piece module, which comes with Perl, replaces localtime with a version that returns\nan object. It also overloads the comparison operators so you can compare them directly:\n\nuse Time::Piece;\nmy $date1 = localtime( $sometime );\nmy $date2 = localtime( $someothertime );\n\nif( $date1 < $date2 ) {\nprint \"The date was in the past\\n\";\n}\n\nYou can also get differences with a subtraction, which returns a Time::Seconds object:\n\nmy $datediff = $date1 - $date2;\nprint \"The difference is \", $datediff->days, \" days\\n\";\n\nIf you want to work with formatted dates, the Date::Manip, Date::Calc, or DateTime modules\ncan help you.\n"
                },
                {
                    "name": "How can I take a string and turn it into epoch seconds?",
                    "content": "If it's a regular enough string that it always has the same format, you can split it up and\npass the parts to \"timelocal\" in the standard Time::Local module. Otherwise, you should look\ninto the Date::Calc, Date::Parse, and Date::Manip modules from CPAN.\n"
                },
                {
                    "name": "How can I find the Julian Day?",
                    "content": "(contributed by brian d foy and Dave Cross)\n\nYou can use the Time::Piece module, part of the Standard Library, which can convert a\ndate/time to a Julian Day:\n\n$ perl -MTime::Piece -le 'print localtime->julianday'\n2455607.7959375\n\nOr the modified Julian Day:\n\n$ perl -MTime::Piece -le 'print localtime->mjd'\n55607.2961226851\n\nOr even the day of the year (which is what some people think of as a Julian day):\n\n$ perl -MTime::Piece -le 'print localtime->yday'\n45\n\nYou can also do the same things with the DateTime module:\n\n$ perl -MDateTime -le'print DateTime->today->jd'\n2453401.5\n$ perl -MDateTime -le'print DateTime->today->mjd'\n53401\n$ perl -MDateTime -le'print DateTime->today->doy'\n31\n\nYou can use the Time::JulianDay module available on CPAN. Ensure that you really want to find\na Julian day, though, as many people have different ideas about Julian days (see\n<http://www.hermetic.ch/calstud/jdn.htm> for instance):\n\n$  perl -MTime::JulianDay -le 'print localjulianday( time )'\n55608\n"
                },
                {
                    "name": "How do I find yesterday's date?",
                    "content": "(contributed by brian d foy)\n\nTo do it correctly, you can use one of the \"Date\" modules since they work with calendars\ninstead of times. The DateTime module makes it simple, and give you the same time of day,\nonly the day before, despite daylight 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\" function.\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 dates, but that\nassumes that days are twenty-four hours each. For most people, there are two days a year when\nthey aren't: the switch to and from 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 standard distribution,\nso you might think that you could do something like 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, and Time::Seconds\nexports the \"ONEDAY\" constant that is a set number of seconds. This means that it always\ngives the time 24 hours ago, which is not always yesterday. This can cause problems around\nthe end of daylight saving 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 answer for those same\nspecial 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"
                },
                {
                    "name": "Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?",
                    "content": "(contributed by brian d foy)\n\nPerl itself never had a Y2K problem, although that never stopped people from creating Y2K\nproblems on their own. See the documentation for \"localtime\" for its proper use.\n\nStarting with Perl 5.12, \"localtime\" and \"gmtime\" can handle dates past 03:14:08 January 19,\n2038, when a 32-bit based time would overflow. You still might get a warning on a 32-bit\n\"perl\":\n\n% perl5.12 -E 'say scalar localtime( 0x9FFFFFFFFFFF )'\nInteger overflow in hexadecimal number at -e line 1.\nWed Nov  1 19:42:39 5576711\n\nOn a 64-bit \"perl\", you can get even larger dates for those really long running projects:\n\n% perl5.12 -E 'say scalar gmtime( 0x9FFFFFFFFFFF )'\nThu Nov  2 00:42:39 5576711\n\nYou're still out of luck if you need to keep track of decaying protons though.\n"
                },
                {
                    "name": "Data: Strings",
                    "content": ""
                },
                {
                    "name": "How do I validate input?",
                    "content": "(contributed by brian d foy)\n\nThere are many ways to ensure that values are what you expect or want to accept. Besides the\nspecific examples that we cover in the perlfaq, you can also look at the modules with\n\"Assert\" and \"Validate\" in their names, along with other modules such as Regexp::Common.\n\nSome modules have validation for particular types of input, such as Business::ISBN,\nBusiness::CreditCard, Email::Valid, and Data::Validate::IP.\n"
                },
                {
                    "name": "How do I unescape a string?",
                    "content": "It depends just what you mean by \"escape\". URL escapes are dealt with in perlfaq9. Shell\nescapes with the backslash (\"\\\") character are removed with\n\ns/\\\\(.)/$1/g;\n\nThis won't expand \"\\n\" or \"\\t\" or any other special escapes.\n"
                },
                {
                    "name": "How do I remove consecutive pairs of characters?",
                    "content": "(contributed by brian d foy)\n\nYou can use the substitution operator to find pairs of characters (or runs of characters) and\nreplace them with a single instance. In this substitution, we find a character in \"(.)\". The\nmemory parentheses store the matched character in the back-reference \"\\g1\" and we use that to\nrequire that the same thing immediately follow it. We replace that part of the string with\nthe character in $1.\n\ns/(.)\\g1/$1/g;\n\nWe can also use the transliteration operator, \"tr///\". In this example, the search list side\nof our \"tr///\" contains nothing, but the \"c\" option complements that so it contains\neverything. The replacement list also contains nothing, so the transliteration is almost a\nno-op since it won't do any replacements (or more exactly, replace the character with\nitself). However, the \"s\" option squashes duplicated and consecutive characters in the string\nso a character does not show up next to itself\n\nmy $str = 'Haarlem';   # in the Netherlands\n$str =~ tr///cs;       # Now Harlem, like in New York\n"
                },
                {
                    "name": "How do I expand function calls in a string?",
                    "content": "(contributed by brian d foy)\n\nThis is documented in perlref, and although it's not the easiest thing to read, it does work.\nIn each of these examples, we call the function inside the braces used to dereference a\nreference. If we have more than one return value, we can construct and dereference an\nanonymous array. In 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 more work. We can\nreally have any code we like inside the braces, so we simply have to end with the scalar\nreference, although how you do that is up to you, and you can use code inside the braces.\nNote that the use of parens creates a list context, so we need \"scalar\" to force the scalar\ncontext 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 the reference\nyourself.\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 specify a variable\nname, in this case \"E\", to set up a tied hash that does the interpolation for you. It has\nseveral other methods to do this as 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, which also forces\nscalar context.\n\nprint \"The time is \" . localtime() . \".\\n\";\n"
                },
                {
                    "name": "How do I find matching/nesting anything?",
                    "content": "To find something between two single characters, a pattern like \"/x([^x]*)x/\" will get the\nintervening bits in $1. For multiple ones, then something more like \"/alpha(.*?)omega/\" would\nbe needed. For nested patterns and/or balanced expressions, see the so-called (?PARNO)\nconstruct (available since perl 5.10).  The CPAN module Regexp::Common can help to build such\nregular expressions (see in particular Regexp::Common::balanced and\nRegexp::Common::delimited).\n\nMore complex cases will require to write a parser, probably using a parsing module from CPAN,\nlike Regexp::Grammars, Parse::RecDescent, Parse::Yapp, Text::Balanced, or Marpa::R2.\n"
                },
                {
                    "name": "How do I reverse a string?",
                    "content": "Use \"reverse()\" in scalar context, as documented in \"reverse\" in perlfunc.\n\nmy $reversed = reverse $string;\n"
                },
                {
                    "name": "How do I expand tabs in a string?",
                    "content": "You 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 distribution).\n\nuse Text::Tabs;\nmy @expandedlines = expand(@lineswithtabs);\n"
                },
                {
                    "name": "How do I reformat a paragraph?",
                    "content": "Use Text::Wrap (part of the standard Perl distribution):\n\nuse Text::Wrap;\nprint wrap(\"\\t\", '  ', @paragraphs);\n\nThe paragraphs you give to Text::Wrap should not contain embedded newlines. Text::Wrap\ndoesn't justify the lines (flush-right).\n\nOr use the CPAN module Text::Autoformat. Formatting files can be easily done by making a\nshell alias, like so:\n\nalias fmt=\"perl -i -MText::Autoformat -n0777 \\\n-e 'print autoformat $, {all=>1}' $*\"\n\nSee the documentation for Text::Autoformat to appreciate its many capabilities.\n"
                },
                {
                    "name": "How can I access or change N characters of a string?",
                    "content": "You can access the first characters of a string with substr().  To get the first character,\nfor example, start at position 0 and grab the string 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 which is the replacement\nstring.\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"
                },
                {
                    "name": "How do I change the Nth occurrence of something?",
                    "content": "You have to keep track of N yourself. For example, let's say you want to change the fifth\noccurrence of \"whoever\" or \"whomever\" into \"whosoever\" or \"whomsoever\", case insensitively.\nThese all assume that $ contains the string to be altered.\n\n$count = 0;\ns{((whom?)ever)}{\n++$count == 5       # is it the 5th?\n? \"${2}soever\"  # yes, swap\n: $1            # renege and leave it there\n}ige;\n\nIn the more general case, you can use the \"/g\" modifier in a \"while\" loop, keeping count of\nmatches.\n\n$WANT = 3;\n$count = 0;\n$ = \"One fish two fish red fish blue fish\";\nwhile (/(\\w+)\\s+fish\\b/gi) {\nif (++$count == $WANT) {\nprint \"The third fish is a $1 one.\\n\";\n}\n}\n\nThat prints out: \"The third fish is a red one.\"  You can also use a repetition count and\nrepeated pattern like this:\n\n/(?:\\w+\\s+fish\\s+){2}(\\w+)\\s+fish/i;\n"
                },
                {
                    "name": "How can I count the number of occurrences of a substring within a string?",
                    "content": "There are a number of ways, with varying efficiency. If you want a count of a certain single\ncharacter (X) within a string, you can use the \"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 you are trying to\ncount multiple character substrings within a larger string, \"tr///\" won't work. What you can\ndo is wrap a while() loop around 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 result to a scalar,\nproducing a count of the number of matches.\n\nmy $count = () = $string =~ /-\\d+/g;\n"
                },
                {
                    "name": "How do I capitalize all the words on one line?",
                    "content": "(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 in there? Wait for\nit... wait for it.... If you answered 5 you're right. Perl words are groups of \"\\w+\", but\nthat's not what you want to capitalize. How is Perl supposed to know not to capitalize that\n\"s\" after 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 Text::Autoformat and get on\nwith the next problem. :)\n"
                },
                {
                    "name": "How can I split a [character]-delimited string except when inside [character]?",
                    "content": "Several modules can handle this sort of parsing--Text::Balanced, Text::CSV, Text::CSVXS, and\nText::ParseWords, among others.\n\nTake the example case of trying to split a string that is comma-separated into its different\nfields. You can't use \"split(/,/)\" because you shouldn't split if the comma is inside quotes.\nFor example, take 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. Thankfully, we have\nJeffrey Friedl, author of Mastering Regular Expressions, to handle these for us. He suggests\n(assuming your string is 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 quotation-mark-delimited field, escape them\nwith backslashes (eg, \"like \\\"this\\\"\".\n\nAlternatively, the Text::ParseWords module (part of the standard Perl distribution) lets you\nsay:\n\nuse Text::ParseWords;\n@new = quotewords(\",\", 0, $text);\n\nFor parsing or generating CSV, though, using Text::CSV rather than implementing it yourself\nis highly recommended; you'll save yourself odd bugs popping up later by just using code\nwhich has already been tried and tested in production for years.\n"
                },
                {
                    "name": "How do I strip blank space from the beginning/end of a string?",
                    "content": "(contributed by brian d foy)\n\nA substitution can do this for you. For a single line, you want to replace all the leading or\ntrailing whitespace with nothing. You can do that with a pair of substitutions:\n\ns/^\\s+//;\ns/\\s+$//;\n\nYou can also write that as a single substitution, although it turns out the combined\nstatement is slower than the separate ones. That might not matter to you, though:\n\ns/^\\s+|\\s+$//g;\n\nIn this regular expression, the alternation matches either at the beginning or the end of the\nstring since the anchors have a lower precedence than the alternation. With the \"/g\" flag,\nthe substitution makes all possible matches, so it gets both. Remember, the trailing newline\nmatches the \"\\s+\", and  the \"$\" anchor can match to the absolute end of the string, so the\nnewline disappears too. Just add the newline to the output, which has the added benefit of\npreserving \"blank\" (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 logical line in the\nstring by adding the \"/m\" flag (for \"multi-line\"). With the \"/m\" flag, the \"$\" matches before\nan embedded newline, so it doesn't remove it. This pattern still removes the newline at the\nend of the string:\n\n$string =~ s/^\\s+|\\s+$//gm;\n\nRemember that lines consisting entirely of whitespace will disappear, since the first part of\nthe alternation can match the entire string and replace it with nothing. If you need to keep\nembedded blank lines, you have to do a little more work. Instead of matching any whitespace\n(since that includes a newline), just match the other whitespace:\n\n$string =~ s/^[\\t\\f ]+|[\\t\\f ]+$//mg;\n"
                },
                {
                    "name": "How do I pad a string with blanks or pad a number with zeroes?",
                    "content": "In the following examples, $padlen is the length to which you wish to pad the string, $text\nor $num contains the string to be padded, and $padchar contains the padding character. You\ncan use a single character string constant instead of the $padchar variable if you know what\nit is in advance. And in the same way you can use an integer in place of $padlen if you know\nthe pad length in advance.\n\nThe simplest method uses the \"sprintf\" function. It can pad on the left or right with blanks\nand on the left with zeroes and it will not truncate the result. The \"pack\" function can only\npad strings on the right 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 one of the following\nmethods. They all generate a pad string with the \"x\" operator and combine that with $text.\nThese methods do not truncate $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"
                },
                {
                    "name": "How do I extract selected columns from a string?",
                    "content": "(contributed by brian d foy)\n\nIf you know the columns that contain the data, you can use \"substr\" to extract a single\ncolumn.\n\nmy $column = substr( $line, $startcolumn, $length );\n\nYou can use \"split\" if the columns are separated by whitespace or some other delimiter, as\nlong as whitespace or the delimiter cannot appear as part 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 that format is a bit\nmore complicated. Use one of the modules that handle that format, such as Text::CSV,\nText::CSVXS, or Text::CSVPP.\n\nIf you want to break apart an entire line of fixed columns, you can use \"unpack\" with the A\n(ASCII) format. By using a number after the format specifier, you can denote the column\nwidth. See the \"pack\" and \"unpack\" entries 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 literal spaces. If you have\nspace separated data, you may want \"split\" instead.\n"
                },
                {
                    "name": "How do I find the soundex value of a string?",
                    "content": "(contributed by brian d foy)\n\nYou can use the \"Text::Soundex\" module. If you want to do fuzzy or close matching, you might\nalso try the String::Approx, and Text::Metaphone, and Text::DoubleMetaphone modules.\n"
                },
                {
                    "name": "How can I expand variables in text strings?",
                    "content": "(contributed by brian d foy)\n\nIf you can avoid it, don't, or if you can use a templating system, such as Text::Template or\nTemplate Toolkit, do that instead. You might even be able to get the job done with \"sprintf\"\nor \"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 full templating system,\nI'll use a string that has two Perl scalar variables in it. In this example, I want to expand\n$foo and $bar to their 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 \"/e\" flag. The first\n\"/e\" evaluates $1 on the replacement side and turns it into $foo. The second /e starts with\n$foo and replaces it with its value. $foo, then, turns into 'Fred', and that's finally what's\nleft in the 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 undefined variable names\nwith the empty string. Since I'm using the \"/e\" flag (twice even!), I have all of the same\nsecurity problems I have with \"eval\" in its string form. If there's something odd in $foo,\nperhaps something like \"@{[ system \"rm -rf /\" ]}\", then I could get myself in trouble.\n\nTo get around the security problem, I could also pull the values from a hash instead of\nevaluating variable names. Using a single \"/e\", I can check the hash to ensure the value\nexists, and if it doesn't, I can replace the missing value with a marker, in this case \"???\"\nto signal that 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"
                },
                {
                    "name": "Does Perl have anything like Ruby's #{} or Python's f string?",
                    "content": "Unlike the others, Perl allows you to embed a variable naked in a double quoted string, e.g.\n\"variable $variable\". When there isn't whitespace or other non-word characters following the\nvariable name, you can add braces (e.g. \"foo ${foo}bar\") to ensure correct parsing.\n\nAn array can also be embedded directly in a string, and will be expanded by default with\nspaces between the elements. The default LISTSEPARATOR can be changed by assigning a\ndifferent string to the special variable $\", such as \"local $\" = ', ';\".\n\nPerl also supports references within a string providing the equivalent of the features in the\nother two languages.\n\n\"${\\ ... }\" embedded within a string will work for most simple statements such as an\nobject->method call. More complex code can be wrapped 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 tools such as\nTemplate::Toolkit and Mojo::Template.\n\nSee also: \"How can I expand variables in text strings?\" and \"How do I expand function calls\nin a string?\" in this FAQ.\n"
                },
                {
                    "name": "What's wrong with always quoting \"$vars\"?",
                    "content": "The problem is that those double-quotes force stringification--coercing numbers and\nreferences into strings--even when you don't want them to be strings. Think of it this way:\ndouble-quote expansion is used to produce new strings. If you already have a string, why do\nyou 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 simpler 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 thing in the scalar\nis actually neither a string nor a number, but a reference:\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 that actually do care\nabout the difference between a string and a number, such as the magical \"++\" autoincrement\noperator or the syscall() function.\n\nStringification also destroys arrays.\n\nmy @lines = `command`;\nprint \"@lines\";     # WRONG - extra blanks\nprint @lines;       # right\n"
                },
                {
                    "name": "Why don't my <<HERE documents work?",
                    "content": "Here documents are found in perlop. Check for these three things:\n\nThere must be no space after the << part.\nThere (probably) should be a semicolon at the end of the opening token\nYou can't (easily) have any space in front of the tag.\nThere needs to be at least a line separator after the end token.\n\nIf you want to indent the text in the here document, you can do this:\n\n# all in one\n(my $VAR = <<HERETARGET) =~ s/^\\s+//gm;\nyour text\ngoes here\nHERETARGET\n\nBut the HERETARGET must still be flush against the margin.  If you want that indented also,\nyou'll have to quote in the indentation.\n\n(my $quote = <<'    FINIS') =~ s/^\\s+//gm;\n...we will have peace, when you and all your works have\nperished--and the works of your dark master to whom you\nwould deliver us. You are a liar, Saruman, and a corrupter\nof men's hearts. --Theoden in /usr/src/perl/taint.c\nFINIS\n$quote =~ s/\\s+--/\\n--/;\n\nA nice general-purpose fixer-upper function for indented here documents follows. It expects\nto be called with a here document as its argument.  It looks to see whether each line begins\nwith a common substring, and if so, strips that substring off. Otherwise, it takes the amount\nof leading whitespace found on the first line and removes that much off each subsequent line.\n\nsub fix {\nlocal $ = shift;\nmy ($white, $leader);  # common whitespace and common leading string\nif (/^\\s*(?:([^\\w\\s]+)(\\s*).*\\n)(?:\\s*\\g1\\g2?.*\\n)+$/) {\n($white, $leader) = ($2, quotemeta($1));\n} else {\n($white, $leader) = (/^(\\s+)/, '');\n}\ns/^\\s*?$leader(?:$white)?//gm;\nreturn $;\n}\n\nThis works with leading special strings, dynamically determined:\n\nmy $rememberthemain = fix<<'    MAININTERPRETERLOOP';\n@@@ int\n@@@ runops() {\n@@@     SAVEI32(runlevel);\n@@@     runlevel++;\n@@@     while ( op = (*op->opppaddr)() );\n@@@     TAINTNOT;\n@@@     return 0;\n@@@ }\nMAININTERPRETERLOOP\n\nOr with a fixed amount of leading whitespace, with remaining indentation correctly preserved:\n\nmy $poem = fix<<EVERONANDON;\nNow far ahead the Road has gone,\nAnd I must follow, if I can,\nPursuing it with eager feet,\nUntil it joins some larger way\nWhere many paths and errands meet.\nAnd whither then? I cannot say.\n--Bilbo in /usr/src/perl/ppctl.c\nEVERONANDON\n\nBeginning with Perl version 5.26, a much simpler and cleaner way to write indented here\ndocuments has been added to the language: the tilde (~) modifier. See \"Indented Here-docs\" in\nperlop for details.\n"
                },
                {
                    "name": "Data: Arrays",
                    "content": ""
                },
                {
                    "name": "What is the difference between a list and an array?",
                    "content": "(contributed by brian d foy)\n\nA list is a fixed collection of scalars. An array is a variable that holds a variable\ncollection of scalars. An array can supply its collection for list operations, so list\noperations 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 subtract some scalars,\nonly work on arrays. These can't work on a list, which is fixed. Array operations include\n\"shift\", \"unshift\", \"push\", \"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 can change a list\nelement. However, the list element is the variable, not the data. You're not changing the\nlist element, but something the list element refers to. The list element itself doesn't\nchange: it's still the same variable.\n\nYou also have to be careful about context. You can assign an array to a scalar to get the\nnumber of elements in the array. This only works for arrays, 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 quite different\nresult. Although it looks like you have a list on the righthand side, Perl actually sees a\nbunch of scalars separated by a comma:\n\nmy $scalar = ( 'dog', 'cat', 'bird' );  # $scalar gets bird\n\nSince you're assigning to a scalar, the righthand side is in scalar context. The comma\noperator (yes, it's an operator!) in scalar context evaluates its lefthand side, throws away\nthe result, and evaluates it's righthand side and returns the result. In effect, that list-\nlookalike assigns to $scalar it's rightmost value. Many people mess this up because they\nchoose a list-lookalike whose last element is also the count they expect:\n\nmy $scalar = ( 1, 2, 3 );  # $scalar gets 3, accidentally\n"
                },
                {
                    "name": "What is the difference between $array[1] and @array[1]?",
                    "content": "(contributed by brian d foy)\n\nThe difference is the sigil, that special character in front of the array name. The \"$\" sigil\nmeans \"exactly one item\", while the \"@\" sigil means \"zero or more items\". The \"$\" gets you a\nsingle scalar, while the \"@\" gets you a list.\n\nThe confusion arises because people incorrectly assume that the sigil denotes the variable\ntype.\n\nThe $array[1] is a single-element access to the array. It's going to return the item in index\n1 (or undef if there is no item there).  If you intend to get exactly one element from the\narray, this is the form you should use.\n\nThe @array[1] is an array slice, although it has only one index.  You can pull out multiple\nelements simultaneously by specifying additional indices as a list, like @array[1,4,3,0].\n\nUsing a slice on the lefthand side of the assignment supplies list context to the righthand\nside. This can lead to unexpected results.  For instance, if you want to read a single line\nfrom a filehandle, assigning to a scalar value is fine:\n\n$array[1] = <STDIN>;\n\nHowever, in list context, the line input operator returns all of the lines as a list. The\nfirst line goes into @array[1] and the rest of the lines mysteriously disappear:\n\n@array[1] = <STDIN>;  # most likely not what you want\n\nEither the \"use warnings\" pragma or the -w flag will warn you when you use an array slice\nwith a single index.\n"
                },
                {
                    "name": "How can I remove duplicate elements from a list or array?",
                    "content": "(contributed by brian d foy)\n\nUse a hash. When you think the words \"unique\" or \"duplicated\", think \"hash keys\".\n\nIf you don't care about the order of the elements, you could just create the hash then\nextract the keys. It's not important how you create that hash: just that you use \"keys\" to\nget 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 List::MoreUtils. In list context it\nreturns the unique elements, preserving their order in the list. In scalar context, it\nreturns the number 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 before. Use a hash to keep\ntrack. The first time the loop sees an element, that element has no key in %Seen. The \"next\"\nstatement creates the 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 time the loop sees\nthat same element, its key exists in the hash and the value for that key is true (since it's\nnot 0 or \"undef\"), so the next 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"
                },
                {
                    "name": "How can I tell whether a certain element is contained in a list or array?",
                    "content": "(portions of this answer contributed by Anno Siegel and brian d foy)\n\nHearing the word \"in\" is an indication that you probably should have used a hash, not a list\nor array, to store your data. Hashes are designed to answer this question quickly and\nefficiently. Arrays aren't.\n\nThat being said, there are several ways to approach this. If you are going to make this query\nmany times over arbitrary string values, the fastest way is probably to invert the original\narray and maintain a hash whose 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 good idea to keep the\nblues all in a hash in the first place.\n\nIf the values are all small integers, you could use a simple indexed array. This kind of an\narray 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 quite a lot of space\nby 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 re-organization of the original\nlist or array. They only pay off if you have to test multiple values against the same array.\n\nIf you are testing only once, the standard module List::Util exports the function \"any\" for\nthis purpose. It works by stopping once it finds the element. It's written in C for speed,\nand its Perl equivalent looks like this 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 context (which returns\nthe number of items that passed its condition) to traverse the entire list. This does have\nthe benefit of telling you how many matches it found, though.\n\nmy $isthere = grep $ eq $whatever, @array;\n\nIf you want to actually extract the matching elements, simply use grep in list context.\n\nmy @matches = grep $ eq $whatever, @array;\n"
                },
                {
                    "name": "How do I compute the difference of two arrays? How do I compute the intersection of two arrays?",
                    "content": "Use a hash. Here's code to do both and more. It assumes that each element is unique in a\ngiven array:\n\nmy (@union, @intersection, @difference);\nmy %count = ();\nforeach my $element (@array1, @array2) { $count{$element}++ }\nforeach my $element (keys %count) {\npush @union, $element;\npush @{ $count{$element} > 1 ? \\@intersection : \\@difference }, $element;\n}\n\nNote that this is the symmetric difference, that is, all elements in either A or in B but not\nin both. Think of it as an xor operation.\n"
                },
                {
                    "name": "How do I test whether two arrays or hashes are equal?",
                    "content": "The following code works for single-level arrays. It uses a stringwise comparison, and does\nnot distinguish defined versus undefined empty strings. 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 this one. It uses the\nCPAN 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 two 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, while the second reports\nthat they do not. Which you prefer is left as an exercise to the reader.\n"
                },
                {
                    "name": "How do I find the first array element for which a condition is true?",
                    "content": "To find the first array element which satisfies a condition, you can use the \"first()\"\nfunction in the List::Util module, which comes with Perl 5.8. This example finds the first\nelement 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 thing. Once you find\nthe 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 \"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 array element at each\nindex until you find one that satisfies the condition:\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"
                },
                {
                    "name": "How do I handle linked lists?",
                    "content": "(contributed by brian d foy)\n\nPerl's arrays do not have a fixed size, so you don't need linked lists if you just want to\nadd or remove items. You can use array operations such as \"push\", \"pop\", \"shift\", \"unshift\",\nor \"splice\" to do that.\n\nSometimes, however, linked lists can be useful in situations where you want to \"shard\" an\narray so you have many small arrays instead of a single big array. You can keep arrays longer\nthan Perl's largest array index, lock smaller arrays separately in threaded programs,\nreallocate less 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 Linked Lists\" (\n<http://www.slideshare.net/lembark/perly-linked-lists> ), although you can just use his\nLinkedList::Single module.\n"
                },
                {
                    "name": "How do I handle circular lists?",
                    "content": "(contributed by brian d foy)\n\nIf you want to cycle through an array endlessly, you can increment the index modulo the\nnumber 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 element of the circular\narray:\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 arrays:\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"
                },
                {
                    "name": "How do I shuffle an array randomly?",
                    "content": "If you either have Perl 5.8.0 or later installed, or if you have Scalar-List-Utils 1.03 or\nlater installed, you can say:\n\nuse List::Util 'shuffle';\n\n@shuffled = shuffle(@list);\n\nIf not, you can use a Fisher-Yates shuffle.\n\nsub fisheryatesshuffle {\nmy $deck = shift;  # $deck is a reference to an array\nreturn unless @$deck; # must not be empty!\n\nmy $i = @$deck;\nwhile (--$i) {\nmy $j = int rand ($i+1);\n@$deck[$i,$j] = @$deck[$j,$i];\n}\n}\n\n# shuffle my mpeg collection\n#\nmy @mpeg = <audio/*/*.mp3>;\nfisheryatesshuffle( \\@mpeg );    # randomize @mpeg in place\nprint @mpeg;\n\nNote that the above implementation shuffles an array in place, unlike the\n\"List::Util::shuffle()\" which takes a list and returns a new shuffled list.\n\nYou've probably seen shuffling algorithms that work using splice, randomly picking another\nelement to swap the current element with\n\nsrand;\n@new = ();\n@old = 1 .. 10;  # just a demo\nwhile (@old) {\npush(@new, splice(@old, rand @old, 1));\n}\n\nThis is bad because splice is already O(N), and since you do it N times, you just invented a\nquadratic algorithm; that is, O(N2).  This does not scale, although Perl is so efficient\nthat you probably won't notice this until you have rather largish arrays.\n"
                },
                {
                    "name": "How do I process/modify each element of an array?",
                    "content": "Use \"for\"/\"foreach\":\n\nfor (@lines) {\ns/foo/bar/;    # change that word\ntr/XZ/ZX/;    # swap those letters\n}\n\nHere's another; let's compute spherical volumes:\n\nmy @volumes = @radii;\nfor (@volumes) {   # @volumes has changed parts\n$ = 3;\n$ *= (4/3) * 3.14159;  # this will be constant folded\n}\n\nwhich can also be done with \"map()\" which is made to transform one list into another:\n\nmy @volumes = map {$  3 * (4/3) * 3.14159} @radii;\n\nIf you want to do the same thing to modify the values of the hash, you can use the \"values\"\nfunction. As of Perl 5.6 the values are not copied, so if you modify $orbit (in this case),\nyou modify the value.\n\nfor my $orbit ( values %orbits ) {\n($orbit = 3) *= (4/3) * 3.14159;\n}\n\nPrior to perl 5.6 \"values\" returned copies of the values, so older perl code often contains\nconstructions such as @orbits{keys %orbits} instead of \"values %orbits\" where the hash is to\nbe modified.\n"
                },
                {
                    "name": "How do I select a random element from an array?",
                    "content": "Use the \"rand()\" function (see \"rand\" in perlfunc):\n\nmy $index   = rand @array;\nmy $element = $array[$index];\n\nOr, simply:\n\nmy $element = $array[ rand @array ];\n"
                },
                {
                    "name": "How do I permute N elements of a list?",
                    "content": "Use the List::Permutor module on CPAN. If the list is actually an array, try the\nAlgorithm::Permute module (also on CPAN). It's written in XS code 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 on each line of\ninput. The algorithm embodied in the \"permute()\" function is discussed in Volume 4 (still\nunpublished) of Knuth's The Art of Computer Programming and will work on any list:\n\n#!/usr/bin/perl -n\n# Fischer-Krause ordered permutation generator\n\nsub permute (&@) {\nmy $code = shift;\nmy @idx = 0..$#;\nwhile ( $code->(@[@idx]) ) {\nmy $p = $#idx;\n--$p while $idx[$p-1] > $idx[$p];\nmy $q = $p or return;\npush @idx, reverse splice @idx, $p;\n++$q while $idx[$p-1] > $idx[$q];\n@idx[$p-1,$q]=@idx[$q,$p-1];\n}\n}\n\npermute { print \"@\\n\" } split;\n\nThe Algorithm::Loops module also provides the \"NextPermute\" and \"NextPermuteNum\" functions\nwhich efficiently find all unique permutations of an array, even if it contains duplicate\nvalues, modifying it in-place: if its elements are in reverse-sorted order then the array is\nreversed, making it sorted, and it returns false; otherwise the next permutation is returned.\n\n\"NextPermute\" uses string order and \"NextPermuteNum\" numeric order, so you can enumerate all\nthe 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"
                },
                {
                    "name": "How do I sort an array by (anything)?",
                    "content": "Supply a comparison function to sort() (described in \"sort\" in perlfunc):\n\n@list = sort { $a <=> $b } @list;\n\nThe default sort function is cmp, string comparison, which would sort \"(1, 2, 10)\" into \"(1,\n10, 2)\". \"<=>\", used above, is the numerical comparison operator.\n\nIf you have a complicated function needed to pull out the part you want to sort on, then\ndon't do it inside the sort function. Pull it out first, because the sort BLOCK can be called\nmany times for the same element. Here's an example of how to pull out the first word after\nthe first number on each item, and then sort those words case-insensitively.\n\nmy @idx;\nfor (@data) {\nmy $item;\n($item) = /\\d+\\s*(\\S+)/;\npush @idx, uc($item);\n}\nmy @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];\n\nwhich could also be written this way, using a trick that's come to be known as the\nSchwartzian Transform:\n\nmy @sorted = map  { $->[0] }\nsort { $a->[1] cmp $b->[1] }\nmap  { [ $, uc( (/\\d+\\s*(\\S+)/)[0]) ] } @data;\n\nIf you need to sort on several fields, the following paradigm is useful.\n\nmy @sorted = sort {\nfield1($a) <=> field1($b) ||\nfield2($a) cmp field2($b) ||\nfield3($a) cmp field3($b)\n} @data;\n\nThis can be conveniently combined with precalculation of keys as given above.\n\nSee the sort article in the \"Far More Than You Ever Wanted To Know\" collection in\n<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> for more about this approach.\n\nSee also the question later in perlfaq4 on sorting hashes.\n"
                },
                {
                    "name": "How do I manipulate arrays of bits?",
                    "content": "Use \"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 would mean that\nyou're wasting a lot of space). To convert an array of bits to a string, use \"vec()\" to set\nthe right bits. This sets $vec to have 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 you had 16 entries\nin @ints, $vec only needs two bytes to store them (not counting the scalar variable\noverhead).\n\nHere's how, given a vector in $vec, you can get those bits into your @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 Tim Bunce and\nWinfried Koenig.)\n\nYou can make the while loop a lot shorter with this suggestion from Benjamin 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 integers and \"big int\"\nmath.\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"
                },
                {
                    "name": "Why does defined() return true on empty arrays and hashes?",
                    "content": "The short story is that you should probably only use defined on scalars or functions, not on\naggregates (arrays and hashes). See \"defined\" in perlfunc in the 5.004 release or later of\nPerl for more detail.\n"
                },
                {
                    "name": "Data: Hashes (Associative Arrays)",
                    "content": ""
                },
                {
                    "name": "How do I process an entire hash?",
                    "content": "(contributed by brian d foy)\n\nThere are a couple of ways that you can process an entire hash. You can get a list of keys,\nthen go through each key, or grab a one key-value pair at a time.\n\nTo go through all of the keys, use the \"keys\" function. This extracts all of the keys of the\nhash and gives them back to you as a list. You can then get the value through the particular\nkey you're processing:\n\nforeach my $key ( keys %hash ) {\nmy $value = $hash{$key}\n...\n}\n\nOnce you have the list of keys, you can process that list before you process the hash\nelements. For instance, you can sort the keys so you can process them in lexical order:\n\nforeach my $key ( sort keys %hash ) {\nmy $value = $hash{$key}\n...\n}\n\nOr, you might want to only process some of the items. If you only want to deal with the keys\nthat start with \"text:\", you can select just those using \"grep\":\n\nforeach my $key ( grep /^text:/, keys %hash ) {\nmy $value = $hash{$key}\n...\n}\n\nIf the hash is very large, you might not want to create a long list of keys. To save some\nmemory, you can grab one key-value pair at a time using \"each()\", which returns a pair you\nhaven't seen yet:\n\nwhile( my( $key, $value ) = each( %hash ) ) {\n...\n}\n\nThe \"each\" operator returns the pairs in apparently random order, so if ordering matters to\nyou, you'll have to stick with the \"keys\" method.\n\nThe \"each()\" operator can be a bit tricky though. You can't add or delete keys of the hash\nwhile you're using it without possibly skipping or re-processing some pairs after Perl\ninternally rehashes all of the elements. Additionally, a hash has only one iterator, so if\nyou mix \"keys\", \"values\", or \"each\" on the same hash, you risk resetting the iterator and\nmessing up your processing. See the \"each\" entry in perlfunc for more details.\n"
                },
                {
                    "name": "How do I merge two hashes?",
                    "content": "(contributed by brian d foy)\n\nBefore you decide to merge two hashes, you have to decide what to do if both hashes contain\nkeys that are the same and if you want to leave the original hashes as they were.\n\nIf you want to preserve the original hashes, copy one hash (%hash1) to a new hash\n(%newhash), then add the keys from the other hash (%hash2 to the new hash. Checking that the\nkey already exists in %newhash gives you a chance to decide what to do with the duplicates:\n\nmy %newhash = %hash1; # make a copy; leave %hash1 alone\n\nforeach my $key2 ( keys %hash2 ) {\nif( exists $newhash{$key2} ) {\nwarn \"Key [$key2] is in both hashes!\";\n# handle the duplicate (perhaps only warning)\n...\nnext;\n}\nelse {\n$newhash{$key2} = $hash2{$key2};\n}\n}\n\nIf you don't want to create a new hash, you can still use this looping technique; just change\nthe %newhash to %hash1.\n\nforeach my $key2 ( keys %hash2 ) {\nif( exists $hash1{$key2} ) {\nwarn \"Key [$key2] is in both hashes!\";\n# handle the duplicate (perhaps only warning)\n...\nnext;\n}\nelse {\n$hash1{$key2} = $hash2{$key2};\n}\n}\n\nIf you don't care that one hash overwrites keys and values from the other, you could just use\na hash slice to add one hash to another. In this case, values from %hash2 replace values from\n%hash1 when they have keys in common:\n\n@hash1{ keys %hash2 } = values %hash2;\n"
                },
                {
                    "name": "What happens if I add or remove keys from a hash while iterating over it?",
                    "content": "(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 recently returned\nwithout worrying about it. If you delete or add other keys, the iterator may skip or double\nup on them since perl may rearrange the hash table. See the entry for \"each()\" in perlfunc.\n"
                },
                {
                    "name": "How do I look up a hash element by value?",
                    "content": "Create a reverse hash:\n\nmy %byvalue = reverse %bykey;\nmy $key = $byvalue{$value};\n\nThat's not particularly efficient. It would be more space-efficient to use:\n\nwhile (my ($key, $value) = each %bykey) {\n$byvalue{$value} = $key;\n}\n\nIf your hash could have repeated values, the methods above will only find one of the\nassociated keys.  This may or may not worry you. If it does worry you, you can always reverse\nthe hash into a hash of arrays instead:\n\nwhile (my ($key, $value) = each %bykey) {\npush @{$keylistbyvalue{$value}}, $key;\n}\n"
                },
                {
                    "name": "How can I know how many entries are in a hash?",
                    "content": "(contributed by brian d foy)\n\nThis is very similar to \"How do I process an entire hash?\", also in perlfaq4, but a bit\nsimpler in the common cases.\n\nYou can use the \"keys()\" built-in function in scalar context to find out have many entries\nyou have in a hash:\n\nmy $keycount = keys %hash; # must be scalar context!\n\nIf you want to find out how many entries have a defined value, that's a bit different. You\nhave to check each value. A \"grep\" is handy:\n\nmy $definedvaluecount = grep { defined } values %hash;\n\nYou can use that same structure to count the entries any way that you like. If you want the\ncount of the keys with vowels in them, you just test for that instead:\n\nmy $vowelcount = grep { /[aeiou]/ } keys %hash;\n\nThe \"grep\" in scalar context returns the count. If you want the list of matching items, just\nuse it in list context instead:\n\nmy @definedvalues = grep { defined } values %hash;\n\nThe \"keys()\" function also resets the iterator, which means that you may see strange results\nif you use this between uses of other hash operators such as \"each()\".\n"
                },
                {
                    "name": "How do I sort a hash (optionally by value instead of key)?",
                    "content": "(contributed by brian d foy)\n\nTo sort a hash, start with the keys. In this example, we give the list of keys to the sort\nfunction which then compares them ASCIIbetically (which might be affected by your locale\nsettings). The output list has the keys in ASCIIbetical order. Once we have the keys, we can\ngo through them 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 the keys, we can\ncompute a value with them and use that value as the comparison.\n\nFor instance, to make our report order case-insensitive, we use \"lc\" to lowercase the keys\nbefore 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 may want to look at\nthe Schwartzian Transform to cache the computation results.\n\nIf we want to sort by the hash value instead, we use the hash key to look it up. We still get\nout a list of keys, but this time they are ordered 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 can provide a\nsecondary 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"
                },
                {
                    "name": "How can I always keep my hash sorted?",
                    "content": "You can look into using the \"DBFile\" module and \"tie()\" using the $DBBTREE hash bindings as\ndocumented in \"In Memory Databases\" in DBFile. The Tie::IxHash module from CPAN might also\nbe instructive. Although this does keep your hash sorted, you might not like the slowdown you\nsuffer from the tie interface. Are you sure you need to do this? :)\n"
                },
                {
                    "name": "What's the difference between \"delete\" and \"undef\" with hashes?",
                    "content": "Hashes contain pairs of scalars: the first is the key, the second is the value. The key will\nbe coerced to a string, although the value can be any kind of scalar: string, number, or\nreference. If a key $key is present in %hash, \"exists($hash{$key})\" will return true. The\nvalue for a given key can be \"undef\", in which case $hash{$key} will be \"undef\" while \"exists\n$hash{$key}\" will return true. This corresponds to ($key, \"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"
                },
                {
                    "name": "Why don't my tied hashes make the defined/exists distinction?",
                    "content": "This depends on the tied hash's implementation of EXISTS().  For example, there isn't the\nconcept of undef with hashes that are tied to DBM* files. It also means that exists() and\ndefined() do the same thing with a DBM* file, and what they end up doing is not what they do\nwith ordinary hashes.\n"
                },
                {
                    "name": "How do I reset an each() operation part-way through?",
                    "content": "(contributed by brian d foy)\n\nYou can use the \"keys\" or \"values\" functions to reset \"each\". To simply reset the iterator\nused by \"each\" without doing anything else, use one of them in void context:\n\nkeys %hash; # resets iterator, nothing else.\nvalues %hash; # resets iterator, nothing else.\n\nSee the documentation for \"each\" in perlfunc.\n"
                },
                {
                    "name": "How can I get the unique keys from two hashes?",
                    "content": "First you extract the keys from the hashes into lists, then solve the \"removing duplicates\"\nproblem described above. For example:\n\nmy %seen = ();\nfor my $element (keys(%foo), keys(%bar)) {\n$seen{$element}++;\n}\nmy @uniq = keys %seen;\n\nOr more succinctly:\n\nmy @uniq = keys %{{%foo,%bar}};\n\nOr if you really want to save space:\n\nmy %seen = ();\nwhile (defined ($key = each %foo)) {\n$seen{$key}++;\n}\nwhile (defined ($key = each %bar)) {\n$seen{$key}++;\n}\nmy @uniq = keys %seen;\n"
                },
                {
                    "name": "How can I store a multidimensional array in a DBM file?",
                    "content": "Either stringify the structure yourself (no fun), or else get the MLDBM (which uses\nData::Dumper) module from CPAN and layer it on top of either DBFile or GDBMFile. You might\nalso try DBM::Deep, but it can be a bit slow.\n"
                },
                {
                    "name": "How can I make my hash remember the order I put elements into it?",
                    "content": "Use 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"
                },
                {
                    "name": "Why does passing a subroutine an undefined element in a hash create it?",
                    "content": "(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 create 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, though.  Since you could\nassign directly to $[0], Perl had to be ready to make that assignment so it created the hash\nkey 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 creates the hash key\nonly 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 because it's a weird\nside effect), you can pass a hash slice instead.  Perl 5.004 didn't make this a special case:\n\nmysub( @hash{ qw/foo/ } );\n"
                },
                {
                    "name": "How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?",
                    "content": "Usually 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 data structures are\ngiven in perldsc and perllol. Examples of structures and object-oriented classes are in\nperlootut.\n"
                },
                {
                    "name": "How can I use a reference as a hash key?",
                    "content": "(contributed by brian d foy and Ben Morrow)\n\nHash keys are strings, so you can't really use a reference as the key.  When you try to do\nthat, perl turns the reference into its stringified form (for instance, \"HASH(0xDEADBEEF)\").\nFrom there you can't get back the reference from the stringified form, at least without doing\nsome extra work on your own.\n\nRemember that the entry in the hash will still be there even if the referenced variable  goes\nout of scope, and that it is entirely possible for Perl to subsequently allocate a different\nvariable at the same address. This will mean a new variable might accidentally be associated\nwith the value for an old.\n\nIf you have Perl 5.10 or later, and you just want to store a value against the reference for\nlookup later, you can use the core Hash::Util::Fieldhash module. This will also handle\nrenaming the keys if you use multiple threads (which causes all variables to be reallocated\nat new addresses, changing their stringification), and garbage-collecting the entries when\nthe referenced variable goes out of scope.\n\nIf you actually need to be able to get a real reference back from each hash entry, you can\nuse the Tie::RefHash module, which does the required work for you.\n"
                },
                {
                    "name": "How can I check if a key exists in a multilevel hash?",
                    "content": "(contributed by brian d foy)\n\nThe trick to this problem is avoiding accidental autovivification. If you want to check three\nkeys 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 \"exists\" you've\ncreated 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 easiest way is to just\nturn it off. The lexical \"autovivification\" pragma is available on CPAN. Now you don't add to\nthe 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\" subroutine can tell you not\nonly if the keys exist but also get the value:\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 before you move onto\nthe next level. This is essentially what Data::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"
                },
                {
                    "name": "How can I prevent addition of unwanted keys into a hash?",
                    "content": "Since version 5.8.0, hashes can be restricted to a fixed number of given keys. Methods for\ncreating and dealing with restricted hashes are exported by the Hash::Util module.\n"
                },
                {
                    "name": "Data: Misc",
                    "content": ""
                },
                {
                    "name": "How do I handle binary data correctly?",
                    "content": "Perl is binary-clean, so it can handle binary data just fine.  On Windows or DOS, however,\nyou have to use \"binmode\" for binary files to avoid conversions for line endings. In general,\nyou should use \"binmode\" any time you want to work with binary data.\n\nAlso see \"binmode\" in perlfunc or perlopentut.\n\nIf you're concerned about 8-bit textual data then see perllocale.  If you want to deal with\nmultibyte characters, however, there are some gotchas. See the section on Regular\nExpressions.\n"
                },
                {
                    "name": "How do I determine whether a scalar is a number/whole/integer/float?",
                    "content": "Assuming that you don't care about IEEE notations like \"NaN\" or \"Infinity\", you probably just\nwant to use a regular expression (see also perlretut and perlre):\n\nuse 5.010;\n\nif ( /\\D/ )\n{ say \"\\thas nondigits\"; }\nif ( /^\\d+\\z/ )\n{ say \"\\tis a whole number\"; }\nif ( /^-?\\d+\\z/ )\n{ say \"\\tis an integer\"; }\nif ( /^[+-]?\\d+\\z/ )\n{ say \"\\tis a +/- integer\"; }\nif ( /^-?(?:\\d+\\.?|\\.\\d)\\d*\\z/ )\n{ say \"\\tis a real number\"; }\nif ( /^[+-]?(?=\\.?\\d)\\d*\\.?\\d*(?:e[+-]?\\d+)?\\z/i )\n{ say \"\\tis a C float\" }\n\nThere are also some commonly used modules for the task.  Scalar::Util (distributed with 5.8)\nprovides access to perl's internal function \"lookslikenumber\" for determining whether a\nvariable looks like a number. Data::Types exports functions that validate data types using\nboth the above and other regular expressions. Thirdly, there is Regexp::Common which has\nregular expressions to match various types of numbers. Those three modules are available from\nthe CPAN.\n\nIf you're on a POSIX system, Perl supports the \"POSIX::strtod\" function for converting\nstrings to doubles (and also \"POSIX::strtol\" for longs). Its semantics are somewhat\ncumbersome, so here's a \"getnum\" wrapper function for more convenient access. This function\ntakes a string and returns the number it found, or \"undef\" for input that isn't a C float.\nThe \"isnumeric\" function is a front end to \"getnum\" if you just want to say, \"Is this a\nfloat?\"\n\nsub getnum {\nuse POSIX qw(strtod);\nmy $str = shift;\n$str =~ s/^\\s+//;\n$str =~ s/\\s+$//;\n$! = 0;\nmy($num, $unparsed) = strtod($str);\nif (($str eq '') || ($unparsed != 0) || $!) {\nreturn undef;\n}\nelse {\nreturn $num;\n}\n}\n\nsub isnumeric { defined getnum($[0]) }\n\nOr you could check out the String::Scanf module on the CPAN instead.\n"
                },
                {
                    "name": "How do I keep persistent data across program calls?",
                    "content": "For some specific applications, you can use one of the DBM modules.  See AnyDBMFile. More\ngenerically, you should consult the FreezeThaw or Storable modules from CPAN. Starting from\nPerl 5.8, Storable is part of the standard distribution. Here's one example using Storable's\n\"store\" and \"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"
                },
                {
                    "name": "How do I print out or copy a recursive data structure?",
                    "content": "The Data::Dumper module on CPAN (or the 5.005 release of Perl) is great for printing out data\nstructures. The Storable module on CPAN (or the 5.8 release of Perl), provides a function\ncalled \"dclone\" that recursively 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.  It will be deeply\ncopied. Because \"dclone\" takes and returns references, you'd have to add extra punctuation if\nyou had a hash of arrays that you wanted to copy.\n\n%newhash = %{ dclone(\\%oldhash) };\n"
                },
                {
                    "name": "How do I define methods for every class/object?",
                    "content": "(contributed by Ben Morrow)\n\nYou can use the \"UNIVERSAL\" class (see UNIVERSAL). However, please be very careful to\nconsider the consequences of doing this: adding methods to every object is very likely to\nhave unintended consequences. If possible, it would be better to have all your object inherit\nfrom some common base class, or to use an object system like Moose that supports roles.\n"
                },
                {
                    "name": "How do I verify a credit card checksum?",
                    "content": "Get the Business::CreditCard module from CPAN.\n"
                },
                {
                    "name": "How do I pack arrays of doubles or floats for XS code?",
                    "content": "The arrays.h/arrays.c code in the PGPLOT module on CPAN does just this.  If you're doing a\nlot of float or double processing, consider using the PDL module from CPAN instead--it makes\nnumber-crunching easy.\n\nSee <https://metacpan.org/release/PGPLOT> for the code.\n"
                }
            ]
        },
        "AUTHOR AND COPYRIGHT": {
            "content": "Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All\nrights reserved.\n\nThis documentation is free; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n\nIrrespective of its distribution, all code examples in this file are hereby placed into the\npublic domain. You are permitted and encouraged to use this code in your own programs for fun\nor for profit as you see fit. A simple comment in the code giving credit would be courteous\nbut is not required.\n\n\n\nperl v5.34.0                                 2025-07-25                                  PERLFAQ4(1)",
            "subsections": []
        }
    },
    "summary": "perlfaq4 - Data Manipulation",
    "flags": [],
    "examples": [],
    "see_also": []
}