{
    "mode": "perldoc",
    "parameter": "ARRAY",
    "section": "-q",
    "url": "https://www.chedong.com/phpMan.php/perldoc/ARRAY/json",
    "generated": "2026-06-15T10:34:31Z",
    "sections": {
        "Found in /usr/share/perl/5.34/pod/perlfaq3.pod": {
            "content": "How can I free an array or hash so my program shrinks?\n(contributed by Michael Carman)\n\nYou usually can't. Memory allocated to lexicals (i.e. my() variables)\ncannot be reclaimed or reused even if they go out of scope. It is\nreserved in case the variables come back into scope. Memory allocated to\nglobal variables can be reused (within your program) by using undef()\nand/or delete().\n\nOn most operating systems, memory allocated to a program can never be\nreturned to the system. That's why long-running programs sometimes re-\nexec themselves. Some operating systems (notably, systems that use",
            "subsections": [
                {
                    "name": "mmap",
                    "content": "is no longer used, but on such systems, perl must be configured and\ncompiled to use the OS's malloc, not perl's.\n\nIn general, memory allocation and de-allocation isn't something you can\nor should be worrying about much in Perl.\n\nSee also \"How can I make my Perl program take less memory?\"\n"
                }
            ]
        },
        "Found in /usr/share/perl/5.34/pod/perlfaq4.pod": {
            "content": "What is the difference between a list and an array?\n(contributed by brian d foy)\n\nA list is a fixed collection of scalars. An array is a variable that\nholds a variable collection of scalars. An array can supply its\ncollection for list operations, so list operations also work on arrays:\n\n# slices\n( 'dog', 'cat', 'bird' )[2,3];\n@animals[2,3];\n\n# iteration\nforeach ( qw( dog cat bird ) ) { ... }\nforeach ( @animals ) { ... }\n\nmy @three = grep { length == 3 } qw( dog cat bird );\nmy @three = grep { length == 3 } @animals;\n\n# supply an argument list\nwashanimals( qw( dog cat bird ) );\nwashanimals( @animals );\n\nArray operations, which change the scalars, rearrange them, or add or\nsubtract some scalars, only work on arrays. These can't work on a list,\nwhich is fixed. Array operations include \"shift\", \"unshift\", \"push\",\n\"pop\", and \"splice\".\n\nAn array can also change its length:\n\n$#animals = 1;  # truncate to two elements\n$#animals = 10000; # pre-extend to 10,001 elements\n\nYou can change an array element, but you can't change a list element:\n\n$animals[0] = 'Rottweiler';\nqw( dog cat bird )[0] = 'Rottweiler'; # syntax error!\n\nforeach ( @animals ) {\ns/^d/fr/;  # works fine\n}\n\nforeach ( qw( dog cat bird ) ) {\ns/^d/fr/;  # Error! Modification of read only value!\n}\n\nHowever, if the list element is itself a variable, it appears that you\ncan change a list element. However, the list element is the variable,\nnot the data. You're not changing the list element, but something the\nlist element refers to. The list element itself doesn't change: it's\nstill the same variable.\n\nYou also have to be careful about context. You can assign an array to a\nscalar to get the number of elements in the array. This only works for\narrays, though:\n\nmy $count = @animals;  # only works with arrays\n\nIf you try to do the same thing with what you think is a list, you get a\nquite different result. Although it looks like you have a list on the\nrighthand side, Perl actually sees a bunch of scalars separated by a\ncomma:\n\nmy $scalar = ( 'dog', 'cat', 'bird' );  # $scalar gets bird\n\nSince you're assigning to a scalar, the righthand side is in scalar\ncontext. The comma operator (yes, it's an operator!) in scalar context\nevaluates its lefthand side, throws away the result, and evaluates it's\nrighthand side and returns the result. In effect, that list-lookalike\nassigns to $scalar it's rightmost value. Many people mess this up\nbecause they choose a list-lookalike whose last element is also the\ncount they expect:\n\nmy $scalar = ( 1, 2, 3 );  # $scalar gets 3, accidentally\n\nWhat is the difference between $array[1] and @array[1]?\n(contributed by brian d foy)\n\nThe difference is the sigil, that special character in front of the\narray name. The \"$\" sigil means \"exactly one item\", while the \"@\" sigil\nmeans \"zero or more items\". The \"$\" gets you a single scalar, while the\n\"@\" gets you a list.\n\nThe confusion arises because people incorrectly assume that the sigil\ndenotes the variable type.\n\nThe $array[1] is a single-element access to the array. It's going to\nreturn the item in index 1 (or undef if there is no item there). If you\nintend to get exactly one element from the array, this is the form you\nshould use.\n\nThe @array[1] is an array slice, although it has only one index. You can\npull out multiple elements simultaneously by specifying additional\nindices as a list, like @array[1,4,3,0].\n\nUsing a slice on the lefthand side of the assignment supplies list\ncontext to the righthand side. This can lead to unexpected results. For\ninstance, if you want to read a single line from a filehandle, assigning\nto a scalar value is fine:\n\n$array[1] = <STDIN>;\n\nHowever, in list context, the line input operator returns all of the\nlines as a list. The first line goes into @array[1] and the rest of the\nlines mysteriously disappear:\n\n@array[1] = <STDIN>;  # most likely not what you want\n\nEither the \"use warnings\" pragma or the -w flag will warn you when you\nuse an array slice with a single index.\n\nHow can I remove duplicate elements from a list or array?\n(contributed by brian d foy)\n\nUse a hash. When you think the words \"unique\" or \"duplicated\", think\n\"hash keys\".\n\nIf you don't care about the order of the elements, you could just create\nthe hash then extract the keys. It's not important how you create that\nhash: just that you use \"keys\" to get the unique elements.\n\nmy %hash   = map { $, 1 } @array;\n# or a hash slice: @hash{ @array } = ();\n# or a foreach: $hash{$} = 1 foreach ( @array );\n\nmy @unique = keys %hash;\n\nIf you want to use a module, try the \"uniq\" function from\nList::MoreUtils. In list context it returns the unique elements,\npreserving their order in the list. In scalar context, it returns the\nnumber of unique elements.\n\nuse List::MoreUtils qw(uniq);\n\nmy @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7\nmy $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7\n\nYou can also go through each element and skip the ones you've seen\nbefore. Use a hash to keep track. The first time the loop sees an\nelement, that element has no key in %Seen. The \"next\" statement creates\nthe key and immediately uses its value, which is \"undef\", so the loop\ncontinues to the \"push\" and increments the value for that key. The next\ntime the loop sees that same element, its key exists in the hash *and*\nthe value for that key is true (since it's not 0 or \"undef\"), so the\nnext skips that iteration and the loop goes to the next element.\n\nmy @unique = ();\nmy %seen   = ();\n\nforeach my $elem ( @array ) {\nnext if $seen{ $elem }++;\npush @unique, $elem;\n}\n\nYou can write this more briefly using a grep, which does the same thing.\n\nmy %seen = ();\nmy @unique = grep { ! $seen{ $ }++ } @array;\n\nHow can I tell whether a certain element is contained in a list or array?\n(portions of this answer contributed by Anno Siegel and brian d foy)\n\nHearing the word \"in\" is an *in*dication that you probably should have\nused a hash, not a list or array, to store your data. Hashes are\ndesigned to answer this question quickly and efficiently. Arrays aren't.\n\nThat being said, there are several ways to approach this. If you are\ngoing to make this query many times over arbitrary string values, the\nfastest way is probably to invert the original array and maintain a hash\nwhose keys are the first array's values:\n\nmy @blues = qw/azure cerulean teal turquoise lapis-lazuli/;\nmy %isblue = ();\nfor (@blues) { $isblue{$} = 1 }\n\nNow you can check whether $isblue{$somecolor}. It might have been a\ngood idea to keep the blues all in a hash in the first place.\n\nIf the values are all small integers, you could use a simple indexed\narray. This kind of an array will take up less space:\n\nmy @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);\nmy @istinyprime = ();\nfor (@primes) { $istinyprime[$] = 1 }\n# or simply  @istinyprime[@primes] = (1) x @primes;\n\nNow you check whether $istinyprime[$somenumber].\n\nIf the values in question are integers instead of strings, you can save\nquite a lot of space by using bit strings instead:\n\nmy @articles = ( 1..10, 150..2000, 2017 );\nundef $read;\nfor (@articles) { vec($read,$,1) = 1 }\n\nNow check whether \"vec($read,$n,1)\" is true for some $n.\n\nThese methods guarantee fast individual tests but require a\nre-organization of the original list or array. They only pay off if you\nhave to test multiple values against the same array.\n\nIf you are testing only once, the standard module List::Util exports the\nfunction \"any\" for this purpose. It works by stopping once it finds the\nelement. It's written in C for speed, and its Perl equivalent looks like\nthis subroutine:\n\nsub any (&@) {\nmy $code = shift;\nforeach (@) {\nreturn 1 if $code->();\n}\nreturn 0;\n}\n\nIf speed is of little concern, the common idiom uses grep in scalar\ncontext (which returns the number of items that passed its condition) to\ntraverse the entire list. This does have the benefit of telling you how\nmany matches it found, though.\n\nmy $isthere = grep $ eq $whatever, @array;\n\nIf you want to actually extract the matching elements, simply use grep\nin list context.\n\nmy @matches = grep $ eq $whatever, @array;\n\nHow do I compute the difference of two arrays? How do I compute the intersection of two arrays?\nUse a hash. Here's code to do both and more. It assumes that each\nelement is unique in a given array:\n\nmy (@union, @intersection, @difference);\nmy %count = ();\nforeach my $element (@array1, @array2) { $count{$element}++ }\nforeach my $element (keys %count) {\npush @union, $element;\npush @{ $count{$element} > 1 ? \\@intersection : \\@difference }, $element;\n}\n\nNote that this is the *symmetric difference*, that is, all elements in\neither A or in B but not in both. Think of it as an xor operation.\n\nHow do I test whether two arrays or hashes are equal?\nThe following code works for single-level arrays. It uses a stringwise\ncomparison, and does not distinguish defined versus undefined empty\nstrings. Modify if you have other needs.\n\n$areequal = comparearrays(\\@frogs, \\@toads);\n\nsub comparearrays {\nmy ($first, $second) = @;\nno warnings;  # silence spurious -w undef complaints\nreturn 0 unless @$first == @$second;\nfor (my $i = 0; $i < @$first; $i++) {\nreturn 0 if $first->[$i] ne $second->[$i];\n}\nreturn 1;\n}\n\nFor multilevel structures, you may wish to use an approach more like\nthis one. It uses the CPAN module FreezeThaw:\n\nuse FreezeThaw qw(cmpStr);\nmy @a = my @b = ( \"this\", \"that\", [ \"more\", \"stuff\" ] );\n\nprintf \"a and b contain %s arrays\\n\",\ncmpStr(\\@a, \\@b) == 0\n? \"the same\"\n: \"different\";\n\nThis approach also works for comparing hashes. Here we'll demonstrate\ntwo different answers:\n\nuse FreezeThaw qw(cmpStr cmpStrHard);\n\nmy %a = my %b = ( \"this\" => \"that\", \"extra\" => [ \"more\", \"stuff\" ] );\n$a{EXTRA} = \\%b;\n$b{EXTRA} = \\%a;\n\nprintf \"a and b contain %s hashes\\n\",\ncmpStr(\\%a, \\%b) == 0 ? \"the same\" : \"different\";\n\nprintf \"a and b contain %s hashes\\n\",\ncmpStrHard(\\%a, \\%b) == 0 ? \"the same\" : \"different\";\n\nThe first reports that both those the hashes contain the same data,\nwhile the second reports that they do not. Which you prefer is left as\nan exercise to the reader.\n\nHow do I find the first array element for which a condition is true?\nTo find the first array element which satisfies a condition, you can use\nthe \"first()\" function in the List::Util module, which comes with Perl\n5.8. This example finds the first element that contains \"Perl\".\n\nuse List::Util qw(first);\n\nmy $element = first { /Perl/ } @array;\n\nIf you cannot use List::Util, you can make your own loop to do the same\nthing. Once you find the element, you stop the loop with last.\n\nmy $found;\nforeach ( @array ) {\nif( /Perl/ ) { $found = $; last }\n}\n\nIf you want the array index, use the \"firstidx()\" function from\n\"List::MoreUtils\":\n\nuse List::MoreUtils qw(firstidx);\nmy $index = firstidx { /Perl/ } @array;\n\nOr write it yourself, iterating through the indices and checking the\narray element at each index until you find one that satisfies the\ncondition:\n\nmy( $found, $index ) = ( undef, -1 );\nfor( $i = 0; $i < @array; $i++ ) {\nif( $array[$i] =~ /Perl/ ) {\n$found = $array[$i];\n$index = $i;\nlast;\n}\n}\n\nHow do I shuffle an array randomly?\nIf you either have Perl 5.8.0 or later installed, or if you have\nScalar-List-Utils 1.03 or later installed, you can say:\n\nuse List::Util 'shuffle';\n\n@shuffled = shuffle(@list);\n\nIf not, you can use a Fisher-Yates shuffle.\n\nsub fisheryatesshuffle {\nmy $deck = shift;  # $deck is a reference to an array\nreturn unless @$deck; # must not be empty!\n\nmy $i = @$deck;\nwhile (--$i) {\nmy $j = int rand ($i+1);\n@$deck[$i,$j] = @$deck[$j,$i];\n}\n}\n\n# shuffle my mpeg collection\n#\nmy @mpeg = <audio/*/*.mp3>;\nfisheryatesshuffle( \\@mpeg );    # randomize @mpeg in place\nprint @mpeg;\n\nNote that the above implementation shuffles an array in place, unlike\nthe \"List::Util::shuffle()\" which takes a list and returns a new\nshuffled list.\n\nYou've probably seen shuffling algorithms that work using splice,\nrandomly picking another element to swap the current element with\n\nsrand;\n@new = ();\n@old = 1 .. 10;  # just a demo\nwhile (@old) {\npush(@new, splice(@old, rand @old, 1));\n}\n\nThis is bad because splice is already O(N), and since you do it N times,\nyou just invented a quadratic algorithm; that is, O(N2). This does not\nscale, although Perl is so efficient that you probably won't notice this\nuntil you have rather largish arrays.\n\nHow do I process/modify each element of an array?\nUse \"for\"/\"foreach\":\n\nfor (@lines) {\ns/foo/bar/;    # change that word\ntr/XZ/ZX/;    # swap those letters\n}\n\nHere's another; let's compute spherical volumes:\n\nmy @volumes = @radii;\nfor (@volumes) {   # @volumes has changed parts\n$ = 3;\n$ *= (4/3) * 3.14159;  # this will be constant folded\n}\n\nwhich can also be done with \"map()\" which is made to transform one list\ninto another:\n\nmy @volumes = map {$  3 * (4/3) * 3.14159} @radii;\n\nIf you want to do the same thing to modify the values of the hash, you\ncan use the \"values\" function. As of Perl 5.6 the values are not copied,\nso if you modify $orbit (in this case), you modify the value.\n\nfor my $orbit ( values %orbits ) {\n($orbit = 3) *= (4/3) * 3.14159;\n}\n\nPrior to perl 5.6 \"values\" returned copies of the values, so older perl\ncode often contains constructions such as @orbits{keys %orbits} instead\nof \"values %orbits\" where the hash is to be modified.\n\nHow do I select a random element from an array?\nUse the \"rand()\" function (see \"rand\" in perlfunc):\n\nmy $index   = rand @array;\nmy $element = $array[$index];\n\nOr, simply:\n\nmy $element = $array[ rand @array ];\n\nHow do I sort an array by (anything)?\nSupply a comparison function to sort() (described in \"sort\" in\nperlfunc):\n\n@list = sort { $a <=> $b } @list;\n\nThe default sort function is cmp, string comparison, which would sort\n\"(1, 2, 10)\" into \"(1, 10, 2)\". \"<=>\", used above, is the numerical\ncomparison operator.\n\nIf you have a complicated function needed to pull out the part you want\nto sort on, then don't do it inside the sort function. Pull it out\nfirst, because the sort BLOCK can be called many times for the same\nelement. Here's an example of how to pull out the first word after the\nfirst number on each item, and then sort those words case-insensitively.\n\nmy @idx;\nfor (@data) {\nmy $item;\n($item) = /\\d+\\s*(\\S+)/;\npush @idx, uc($item);\n}\nmy @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];\n\nwhich could also be written this way, using a trick that's come to be\nknown as the Schwartzian Transform:\n\nmy @sorted = map  { $->[0] }\nsort { $a->[1] cmp $b->[1] }\nmap  { [ $, uc( (/\\d+\\s*(\\S+)/)[0]) ] } @data;\n\nIf you need to sort on several fields, the following paradigm is useful.\n\nmy @sorted = sort {\nfield1($a) <=> field1($b) ||\nfield2($a) cmp field2($b) ||\nfield3($a) cmp field3($b)\n} @data;\n\nThis can be conveniently combined with precalculation of keys as given\nabove.\n\nSee the sort article in the \"Far More Than You Ever Wanted To Know\"\ncollection in <http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> for more\nabout this approach.\n\nSee also the question later in perlfaq4 on sorting hashes.\n\nHow do I manipulate arrays of bits?\nUse \"pack()\" and \"unpack()\", or else \"vec()\" and the bitwise operations.\n\nFor example, you don't have to store individual bits in an array (which\nwould mean that you're wasting a lot of space). To convert an array of\nbits to a string, use \"vec()\" to set the right bits. This sets $vec to\nhave bit N set only if $ints[N] was set:\n\nmy @ints = (...); # array of bits, e.g. ( 1, 0, 0, 1, 1, 0 ... )\nmy $vec = '';\nforeach( 0 .. $#ints ) {\nvec($vec,$,1) = 1 if $ints[$];\n}\n\nThe string $vec only takes up as many bits as it needs. For instance, if\nyou had 16 entries in @ints, $vec only needs two bytes to store them\n(not counting the scalar variable overhead).\n\nHere's how, given a vector in $vec, you can get those bits into your\n@ints array:\n\nsub bitvectolist {\nmy $vec = shift;\nmy @ints;\n# Find null-byte density then select best algorithm\nif ($vec =~ tr/\\0// / length $vec > 0.95) {\nuse integer;\nmy $i;\n\n# This method is faster with mostly null-bytes\nwhile($vec =~ /[^\\0]/g ) {\n$i = -9 + 8 * pos $vec;\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\npush @ints, $i if vec($vec, ++$i, 1);\n}\n}\nelse {\n# This method is a fast general algorithm\nuse integer;\nmy $bits = unpack \"b*\", $vec;\npush @ints, 0 if $bits =~ s/^(\\d)// && $1;\npush @ints, pos $bits while($bits =~ /1/g);\n}\n\nreturn \\@ints;\n}\n\nThis method gets faster the more sparse the bit vector is. (Courtesy of\nTim Bunce and Winfried Koenig.)\n\nYou can make the while loop a lot shorter with this suggestion from\nBenjamin Goldberg:\n\nwhile($vec =~ /[^\\0]+/g ) {\npush @ints, grep vec($vec, $, 1), $-[0] * 8 .. $+[0] * 8;\n}\n\nOr use the CPAN module Bit::Vector:\n\nmy $vector = Bit::Vector->new($numofbits);\n$vector->IndexListStore(@ints);\nmy @ints = $vector->IndexListRead();\n\nBit::Vector provides efficient methods for bit vector, sets of small\nintegers and \"big int\" math.\n\nHere's a more extensive illustration using vec():\n\n# vec demo\nmy $vector = \"\\xff\\x0f\\xef\\xfe\";\nprint \"Ilya's string \\\\xff\\\\x0f\\\\xef\\\\xfe represents the number \",\nunpack(\"N\", $vector), \"\\n\";\nmy $isset = vec($vector, 23, 1);\nprint \"Its 23rd bit is \", $isset ? \"set\" : \"clear\", \".\\n\";\npvec($vector);\n\nsetvec(1,1,1);\nsetvec(3,1,1);\nsetvec(23,1,1);\n\nsetvec(3,1,3);\nsetvec(3,2,3);\nsetvec(3,4,3);\nsetvec(3,4,7);\nsetvec(3,8,3);\nsetvec(3,8,7);\n\nsetvec(0,32,17);\nsetvec(1,32,17);\n\nsub setvec {\nmy ($offset, $width, $value) = @;\nmy $vector = '';\nvec($vector, $offset, $width) = $value;\nprint \"offset=$offset width=$width value=$value\\n\";\npvec($vector);\n}\n\nsub pvec {\nmy $vector = shift;\nmy $bits = unpack(\"b*\", $vector);\nmy $i = 0;\nmy $BASE = 8;\n\nprint \"vector length in bytes: \", length($vector), \"\\n\";\n@bytes = unpack(\"A8\" x length($vector), $bits);\nprint \"bits are: @bytes\\n\\n\";\n}\n\nWhy does defined() return true on empty arrays and hashes?\nThe short story is that you should probably only use defined on scalars\nor functions, not on aggregates (arrays and hashes). See \"defined\" in\nperlfunc in the 5.004 release or later of Perl for more detail.\n\nHow can I store a multidimensional array in a DBM file?\nEither stringify the structure yourself (no fun), or else get the MLDBM\n(which uses Data::Dumper) module from CPAN and layer it on top of either\nDBFile or GDBMFile. You might also try DBM::Deep, but it can be a bit\nslow.\n\nHow can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?\nUsually a hash ref, perhaps like this:\n\n$record = {\nNAME   => \"Jason\",\nEMPNO  => 132,\nTITLE  => \"deputy peon\",\nAGE    => 23,\nSALARY => 37000,\nPALS   => [ \"Norbert\", \"Rhys\", \"Phineas\"],\n};\n\nReferences are documented in perlref and perlreftut. Examples of complex\ndata structures are given in perldsc and perllol. Examples of structures\nand object-oriented classes are in perlootut.\n\nHow do I pack arrays of doubles or floats for XS code?\nThe arrays.h/arrays.c code in the PGPLOT module on CPAN does just this.\nIf you're doing a lot of float or double processing, consider using the\nPDL module from CPAN instead--it makes number-crunching easy.\n\nSee <https://metacpan.org/release/PGPLOT> for the code.\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.34/pod/perlfaq5.pod": {
            "content": "How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles?\nAs of perl5.6, open() autovivifies file and directory handles as\nreferences if you pass it an uninitialized scalar variable. You can then\npass these references just like any other scalar, and use them in the\nplace of named handles.\n\nopen my    $fh, $filename;\n\nopen local $fh, $filename;\n\nprint $fh \"Hello World!\\n\";\n\nprocessfile( $fh );\n\nIf you like, you can store these filehandles in an array or a hash. If\nyou access them directly, they aren't simple scalars and you need to\ngive \"print\" a little help by placing the filehandle reference in\nbraces. Perl can only figure it out on its own when the filehandle\nreference is a simple scalar.\n\nmy @fhs = ( $fh1, $fh2, $fh3 );\n\nfor( $i = 0; $i <= $#fhs; $i++ ) {\nprint {$fhs[$i]} \"just another Perl answer, \\n\";\n}\n\nBefore perl5.6, you had to deal with various typeglob idioms which you\nmay see in older code.\n\nopen FILE, \"> $filename\";\nprocesstypeglob(   *FILE );\nprocessreference( \\*FILE );\n\nsub processtypeglob  { local *FH = shift; print FH  \"Typeglob!\" }\nsub processreference { local $fh = shift; print $fh \"Reference!\" }\n\nIf you want to create many anonymous handles, you should check out the\nSymbol or IO::Handle modules.\n\nWhy do I get weird spaces when I print an array of lines?\n(contributed by brian d foy)\n\nIf you are seeing spaces between the elements of your array when you\nprint the array, you are probably interpolating the array in double\nquotes:\n\nmy @animals = qw(camel llama alpaca vicuna);\nprint \"animals are: @animals\\n\";\n\nIt's the double quotes, not the \"print\", doing this. Whenever you\ninterpolate an array in a double quote context, Perl joins the elements\nwith spaces (or whatever is in $\", which is a space by default):\n\nanimals are: camel llama alpaca vicuna\n\nThis is different than printing the array without the interpolation:\n\nmy @animals = qw(camel llama alpaca vicuna);\nprint \"animals are: \", @animals, \"\\n\";\n\nNow the output doesn't have the spaces between the elements because the\nelements of @animals simply become part of the list to \"print\":\n\nanimals are: camelllamaalpacavicuna\n\nYou might notice this when each of the elements of @array end with a\nnewline. You expect to print one element per line, but notice that every\nline after the first is indented:\n\nthis is a line\nthis is another line\nthis is the third line\n\nThat extra space comes from the interpolation of the array. If you don't\nwant to put anything between your array elements, don't use the array in\ndouble quotes. You can send it to print without them:\n\nprint @lines;\n",
            "subsections": []
        },
        "Found in /usr/share/perl/5.34/pod/perlfaq7.pod": {
            "content": "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?\nYou need to pass references to these objects. See \"Pass by Reference\" in\nperlsub for this particular question, and perlref for information on\nreferences.\n\nPassing Variables and Functions\nRegular variables and functions are quite easy to pass: just pass in\na reference to an existing or anonymous variable or function:\n\nfunc( \\$somescalar );\n\nfunc( \\@somearray  );\nfunc( [ 1 .. 10 ]   );\n\nfunc( \\%somehash   );\nfunc( { this => 10, that => 20 }   );\n\nfunc( \\&somefunc   );\nfunc( sub { $[0]  $[1] }   );\n\nPassing Filehandles\nAs of Perl 5.6, you can represent filehandles with scalar variables\nwhich you treat as any other scalar.\n\nopen my $fh, $filename or die \"Cannot open $filename! $!\";\nfunc( $fh );\n\nsub func {\nmy $passedfh = shift;\n\nmy $line = <$passedfh>;\n}\n\nBefore Perl 5.6, you had to use the *FH or \"\\*FH\" notations. These\nare \"typeglobs\"--see \"Typeglobs and Filehandles\" in perldata and\nespecially \"Pass by Reference\" in perlsub for more information.\n\nPassing Regexes\nHere's an example of how to pass in a string and a regular\nexpression for it to match against. You construct the pattern with\nthe \"qr//\" operator:\n\nsub compare {\nmy ($val1, $regex) = @;\nmy $retval = $val1 =~ /$regex/;\nreturn $retval;\n}\n$match = compare(\"old McDonald\", qr/d.*D/i);\n\nPassing Methods\nTo pass an object method into a subroutine, you can do this:\n\ncallalot(10, $someobj, \"methname\")\nsub callalot {\nmy ($count, $widget, $trick) = @;\nfor (my $i = 0; $i < $count; $i++) {\n$widget->$trick();\n}\n}\n\nOr, you can use a closure to bundle up the object, its method call,\nand arguments:\n\nmy $whatnot = sub { $someobj->obfuscate(@args) };\nfunc($whatnot);\nsub func {\nmy $code = shift;\n&$code();\n}\n\nYou could also investigate the can() method in the UNIVERSAL class\n(part of the standard perl distribution).\n",
            "subsections": []
        }
    },
    "flags": [],
    "examples": [],
    "see_also": []
}