Found in /usr/share/perl/5.34/pod/perlfaq3.pod How can I free an array or hash so my program shrinks? (contributed by Michael Carman) You usually can't. Memory allocated to lexicals (i.e. my() variables) cannot be reclaimed or reused even if they go out of scope. It is reserved in case the variables come back into scope. Memory allocated to global variables can be reused (within your program) by using undef() and/or delete(). On most operating systems, memory allocated to a program can never be returned to the system. That's why long-running programs sometimes re- exec themselves. Some operating systems (notably, systems that use mmap(2) for allocating large chunks of memory) can reclaim memory that is no longer used, but on such systems, perl must be configured and compiled to use the OS's malloc, not perl's. In general, memory allocation and de-allocation isn't something you can or should be worrying about much in Perl. See also "How can I make my Perl program take less memory?" Found in /usr/share/perl/5.34/pod/perlfaq4.pod What is the difference between a list and an array? (contributed by brian d foy) A list is a fixed collection of scalars. An array is a variable that holds a variable collection of scalars. An array can supply its collection for list operations, so list operations also work on arrays: # slices ( 'dog', 'cat', 'bird' )[2,3]; @animals[2,3]; # iteration foreach ( qw( dog cat bird ) ) { ... } foreach ( @animals ) { ... } my @three = grep { length == 3 } qw( dog cat bird ); my @three = grep { length == 3 } @animals; # supply an argument list wash_animals( qw( dog cat bird ) ); wash_animals( @animals ); Array operations, which change the scalars, rearrange them, or add or subtract some scalars, only work on arrays. These can't work on a list, which is fixed. Array operations include "shift", "unshift", "push", "pop", and "splice". An array can also change its length: $#animals = 1; # truncate to two elements $#animals = 10000; # pre-extend to 10,001 elements You can change an array element, but you can't change a list element: $animals[0] = 'Rottweiler'; qw( dog cat bird )[0] = 'Rottweiler'; # syntax error! foreach ( @animals ) { s/^d/fr/; # works fine } foreach ( qw( dog cat bird ) ) { s/^d/fr/; # Error! Modification of read only value! } However, if the list element is itself a variable, it appears that you can change a list element. However, the list element is the variable, not the data. You're not changing the list element, but something the list element refers to. The list element itself doesn't change: it's still the same variable. You also have to be careful about context. You can assign an array to a scalar to get the number of elements in the array. This only works for arrays, though: my $count = @animals; # only works with arrays If you try to do the same thing with what you think is a list, you get a quite different result. Although it looks like you have a list on the righthand side, Perl actually sees a bunch of scalars separated by a comma: my $scalar = ( 'dog', 'cat', 'bird' ); # $scalar gets bird Since you're assigning to a scalar, the righthand side is in scalar context. The comma operator (yes, it's an operator!) in scalar context evaluates its lefthand side, throws away the result, and evaluates it's righthand side and returns the result. In effect, that list-lookalike assigns to $scalar it's rightmost value. Many people mess this up because they choose a list-lookalike whose last element is also the count they expect: my $scalar = ( 1, 2, 3 ); # $scalar gets 3, accidentally What is the difference between $array[1] and @array[1]? (contributed by brian d foy) The difference is the sigil, that special character in front of the array name. The "$" sigil means "exactly one item", while the "@" sigil means "zero or more items". The "$" gets you a single scalar, while the "@" gets you a list. The confusion arises because people incorrectly assume that the sigil denotes the variable type. The $array[1] is a single-element access to the array. It's going to return the item in index 1 (or undef if there is no item there). If you intend to get exactly one element from the array, this is the form you should use. The @array[1] is an array slice, although it has only one index. You can pull out multiple elements simultaneously by specifying additional indices as a list, like @array[1,4,3,0]. Using a slice on the lefthand side of the assignment supplies list context to the righthand side. This can lead to unexpected results. For instance, if you want to read a single line from a filehandle, assigning to a scalar value is fine: $array[1] = <STDIN>; However, in list context, the line input operator returns all of the lines as a list. The first line goes into @array[1] and the rest of the lines mysteriously disappear: @array[1] = <STDIN>; # most likely not what you want Either the "use warnings" pragma or the -w flag will warn you when you use an array slice with a single index. How can I remove duplicate elements from a list or array? (contributed by brian d foy) Use a hash. When you think the words "unique" or "duplicated", think "hash keys". If you don't care about the order of the elements, you could just create the hash then extract the keys. It's not important how you create that hash: just that you use "keys" to get the unique elements. my %hash = map { $_, 1 } @array; # or a hash slice: @hash{ @array } = (); # or a foreach: $hash{$_} = 1 foreach ( @array ); my @unique = keys %hash; If you want to use a module, try the "uniq" function from List::MoreUtils. In list context it returns the unique elements, preserving their order in the list. In scalar context, it returns the number of unique elements. use List::MoreUtils qw(uniq); my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7 my $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7 You can also go through each element and skip the ones you've seen before. Use a hash to keep track. The first time the loop sees an element, that element has no key in %Seen. The "next" statement creates the key and immediately uses its value, which is "undef", so the loop continues to the "push" and increments the value for that key. The next time the loop sees that same element, its key exists in the hash *and* the value for that key is true (since it's not 0 or "undef"), so the next skips that iteration and the loop goes to the next element. my @unique = (); my %seen = (); foreach my $elem ( @array ) { next if $seen{ $elem }++; push @unique, $elem; } You can write this more briefly using a grep, which does the same thing. my %seen = (); my @unique = grep { ! $seen{ $_ }++ } @array; How can I tell whether a certain element is contained in a list or array? (portions of this answer contributed by Anno Siegel and brian d foy) Hearing the word "in" is an *in*dication that you probably should have used a hash, not a list or array, to store your data. Hashes are designed to answer this question quickly and efficiently. Arrays aren't. That being said, there are several ways to approach this. If you are going to make this query many times over arbitrary string values, the fastest way is probably to invert the original array and maintain a hash whose keys are the first array's values: my @blues = qw/azure cerulean teal turquoise lapis-lazuli/; my %is_blue = (); for (@blues) { $is_blue{$_} = 1 } Now you can check whether $is_blue{$some_color}. It might have been a good idea to keep the blues all in a hash in the first place. If the values are all small integers, you could use a simple indexed array. This kind of an array will take up less space: my @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31); my @is_tiny_prime = (); for (@primes) { $is_tiny_prime[$_] = 1 } # or simply @istiny_prime[@primes] = (1) x @primes; Now you check whether $is_tiny_prime[$some_number]. If the values in question are integers instead of strings, you can save quite a lot of space by using bit strings instead: my @articles = ( 1..10, 150..2000, 2017 ); undef $read; for (@articles) { vec($read,$_,1) = 1 } Now check whether "vec($read,$n,1)" is true for some $n. These methods guarantee fast individual tests but require a re-organization of the original list or array. They only pay off if you have to test multiple values against the same array. If you are testing only once, the standard module List::Util exports the function "any" for this purpose. It works by stopping once it finds the element. It's written in C for speed, and its Perl equivalent looks like this subroutine: sub any (&@) { my $code = shift; foreach (@_) { return 1 if $code->(); } return 0; } If speed is of little concern, the common idiom uses grep in scalar context (which returns the number of items that passed its condition) to traverse the entire list. This does have the benefit of telling you how many matches it found, though. my $is_there = grep $_ eq $whatever, @array; If you want to actually extract the matching elements, simply use grep in list context. my @matches = grep $_ eq $whatever, @array; How do I compute the difference of two arrays? How do I compute the intersection of two arrays? Use a hash. Here's code to do both and more. It assumes that each element is unique in a given array: my (@union, @intersection, @difference); my %count = (); foreach my $element (@array1, @array2) { $count{$element}++ } foreach my $element (keys %count) { push @union, $element; push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element; } Note that this is the *symmetric difference*, that is, all elements in either A or in B but not in both. Think of it as an xor operation. How do I test whether two arrays or hashes are equal? The following code works for single-level arrays. It uses a stringwise comparison, and does not distinguish defined versus undefined empty strings. Modify if you have other needs. $are_equal = compare_arrays(\@frogs, \@toads); sub compare_arrays { my ($first, $second) = @_; no warnings; # silence spurious -w undef complaints return 0 unless @$first == @$second; for (my $i = 0; $i < @$first; $i++) { return 0 if $first->[$i] ne $second->[$i]; } return 1; } For multilevel structures, you may wish to use an approach more like this one. It uses the CPAN module FreezeThaw: use FreezeThaw qw(cmpStr); my @a = my @b = ( "this", "that", [ "more", "stuff" ] ); printf "a and b contain %s arrays\n", cmpStr(\@a, \@b) == 0 ? "the same" : "different"; This approach also works for comparing hashes. Here we'll demonstrate two different answers: use FreezeThaw qw(cmpStr cmpStrHard); my %a = my %b = ( "this" => "that", "extra" => [ "more", "stuff" ] ); $a{EXTRA} = \%b; $b{EXTRA} = \%a; printf "a and b contain %s hashes\n", cmpStr(\%a, \%b) == 0 ? "the same" : "different"; printf "a and b contain %s hashes\n", cmpStrHard(\%a, \%b) == 0 ? "the same" : "different"; The first reports that both those the hashes contain the same data, while the second reports that they do not. Which you prefer is left as an exercise to the reader. How do I find the first array element for which a condition is true? To find the first array element which satisfies a condition, you can use the "first()" function in the List::Util module, which comes with Perl 5.8. This example finds the first element that contains "Perl". use List::Util qw(first); my $element = first { /Perl/ } @array; If you cannot use List::Util, you can make your own loop to do the same thing. Once you find the element, you stop the loop with last. my $found; foreach ( @array ) { if( /Perl/ ) { $found = $_; last } } If you want the array index, use the "firstidx()" function from "List::MoreUtils": use List::MoreUtils qw(firstidx); my $index = firstidx { /Perl/ } @array; Or write it yourself, iterating through the indices and checking the array element at each index until you find one that satisfies the condition: my( $found, $index ) = ( undef, -1 ); for( $i = 0; $i < @array; $i++ ) { if( $array[$i] =~ /Perl/ ) { $found = $array[$i]; $index = $i; last; } } How do I shuffle an array randomly? If you either have Perl 5.8.0 or later installed, or if you have Scalar-List-Utils 1.03 or later installed, you can say: use List::Util 'shuffle'; @shuffled = shuffle(@list); If not, you can use a Fisher-Yates shuffle. sub fisher_yates_shuffle { my $deck = shift; # $deck is a reference to an array return unless @$deck; # must not be empty! my $i = @$deck; while (--$i) { my $j = int rand ($i+1); @$deck[$i,$j] = @$deck[$j,$i]; } } # shuffle my mpeg collection # my @mpeg = <audio/*/*.mp3>; fisher_yates_shuffle( \@mpeg ); # randomize @mpeg in place print @mpeg; Note that the above implementation shuffles an array in place, unlike the "List::Util::shuffle()" which takes a list and returns a new shuffled list. You've probably seen shuffling algorithms that work using splice, randomly picking another element to swap the current element with srand; @new = (); @old = 1 .. 10; # just a demo while (@old) { push(@new, splice(@old, rand @old, 1)); } This is bad because splice is already O(N), and since you do it N times, you just invented a quadratic algorithm; that is, O(N**2). This does not scale, although Perl is so efficient that you probably won't notice this until you have rather largish arrays. How do I process/modify each element of an array? Use "for"/"foreach": for (@lines) { s/foo/bar/; # change that word tr/XZ/ZX/; # swap those letters } Here's another; let's compute spherical volumes: my @volumes = @radii; for (@volumes) { # @volumes has changed parts $_ **= 3; $_ *= (4/3) * 3.14159; # this will be constant folded } which can also be done with "map()" which is made to transform one list into another: my @volumes = map {$_ ** 3 * (4/3) * 3.14159} @radii; If you want to do the same thing to modify the values of the hash, you can use the "values" function. As of Perl 5.6 the values are not copied, so if you modify $orbit (in this case), you modify the value. for my $orbit ( values %orbits ) { ($orbit **= 3) *= (4/3) * 3.14159; } Prior to perl 5.6 "values" returned copies of the values, so older perl code often contains constructions such as @orbits{keys %orbits} instead of "values %orbits" where the hash is to be modified. How do I select a random element from an array? Use the "rand()" function (see "rand" in perlfunc): my $index = rand @array; my $element = $array[$index]; Or, simply: my $element = $array[ rand @array ]; How do I sort an array by (anything)? Supply a comparison function to sort() (described in "sort" in perlfunc): @list = sort { $a <=> $b } @list; The default sort function is cmp, string comparison, which would sort "(1, 2, 10)" into "(1, 10, 2)". "<=>", used above, is the numerical comparison operator. If you have a complicated function needed to pull out the part you want to sort on, then don't do it inside the sort function. Pull it out first, because the sort BLOCK can be called many times for the same element. Here's an example of how to pull out the first word after the first number on each item, and then sort those words case-insensitively. my @idx; for (@data) { my $item; ($item) = /\d+\s*(\S+)/; push @idx, uc($item); } my @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ]; which could also be written this way, using a trick that's come to be known as the Schwartzian Transform: my @sorted = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [ $_, uc( (/\d+\s*(\S+)/)[0]) ] } @data; If you need to sort on several fields, the following paradigm is useful. my @sorted = sort { field1($a) <=> field1($b) || field2($a) cmp field2($b) || field3($a) cmp field3($b) } @data; This can be conveniently combined with precalculation of keys as given above. See the sort article in the "Far More Than You Ever Wanted To Know" collection in <http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> for more about this approach. See also the question later in perlfaq4 on sorting hashes. How do I manipulate arrays of bits? Use "pack()" and "unpack()", or else "vec()" and the bitwise operations. For example, you don't have to store individual bits in an array (which would mean that you're wasting a lot of space). To convert an array of bits to a string, use "vec()" to set the right bits. This sets $vec to have bit N set only if $ints[N] was set: my @ints = (...); # array of bits, e.g. ( 1, 0, 0, 1, 1, 0 ... ) my $vec = ''; foreach( 0 .. $#ints ) { vec($vec,$_,1) = 1 if $ints[$_]; } The string $vec only takes up as many bits as it needs. For instance, if you had 16 entries in @ints, $vec only needs two bytes to store them (not counting the scalar variable overhead). Here's how, given a vector in $vec, you can get those bits into your @ints array: sub bitvec_to_list { my $vec = shift; my @ints; # Find null-byte density then select best algorithm if ($vec =~ tr/\0// / length $vec > 0.95) { use integer; my $i; # This method is faster with mostly null-bytes while($vec =~ /[^\0]/g ) { $i = -9 + 8 * pos $vec; push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); } } else { # This method is a fast general algorithm use integer; my $bits = unpack "b*", $vec; push @ints, 0 if $bits =~ s/^(\d)// && $1; push @ints, pos $bits while($bits =~ /1/g); } return \@ints; } This method gets faster the more sparse the bit vector is. (Courtesy of Tim Bunce and Winfried Koenig.) You can make the while loop a lot shorter with this suggestion from Benjamin Goldberg: while($vec =~ /[^\0]+/g ) { push @ints, grep vec($vec, $_, 1), $-[0] * 8 .. $+[0] * 8; } Or use the CPAN module Bit::Vector: my $vector = Bit::Vector->new($num_of_bits); $vector->Index_List_Store(@ints); my @ints = $vector->Index_List_Read(); Bit::Vector provides efficient methods for bit vector, sets of small integers and "big int" math. Here's a more extensive illustration using vec(): # vec demo my $vector = "\xff\x0f\xef\xfe"; print "Ilya's string \\xff\\x0f\\xef\\xfe represents the number ", unpack("N", $vector), "\n"; my $is_set = vec($vector, 23, 1); print "Its 23rd bit is ", $is_set ? "set" : "clear", ".\n"; pvec($vector); set_vec(1,1,1); set_vec(3,1,1); set_vec(23,1,1); set_vec(3,1,3); set_vec(3,2,3); set_vec(3,4,3); set_vec(3,4,7); set_vec(3,8,3); set_vec(3,8,7); set_vec(0,32,17); set_vec(1,32,17); sub set_vec { my ($offset, $width, $value) = @_; my $vector = ''; vec($vector, $offset, $width) = $value; print "offset=$offset width=$width value=$value\n"; pvec($vector); } sub pvec { my $vector = shift; my $bits = unpack("b*", $vector); my $i = 0; my $BASE = 8; print "vector length in bytes: ", length($vector), "\n"; @bytes = unpack("A8" x length($vector), $bits); print "bits are: @bytes\n\n"; } Why does defined() return true on empty arrays and hashes? The short story is that you should probably only use defined on scalars or functions, not on aggregates (arrays and hashes). See "defined" in perlfunc in the 5.004 release or later of Perl for more detail. How can I store a multidimensional array in a DBM file? Either stringify the structure yourself (no fun), or else get the MLDBM (which uses Data::Dumper) module from CPAN and layer it on top of either DB_File or GDBM_File. You might also try DBM::Deep, but it can be a bit slow. How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays? Usually a hash ref, perhaps like this: $record = { NAME => "Jason", EMPNO => 132, TITLE => "deputy peon", AGE => 23, SALARY => 37_000, PALS => [ "Norbert", "Rhys", "Phineas"], }; References are documented in perlref and perlreftut. Examples of complex data structures are given in perldsc and perllol. Examples of structures and object-oriented classes are in perlootut. How do I pack arrays of doubles or floats for XS code? The arrays.h/arrays.c code in the PGPLOT module on CPAN does just this. If you're doing a lot of float or double processing, consider using the PDL module from CPAN instead--it makes number-crunching easy. See <https://metacpan.org/release/PGPLOT> for the code. Found in /usr/share/perl/5.34/pod/perlfaq5.pod 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? As of perl5.6, open() autovivifies file and directory handles as references if you pass it an uninitialized scalar variable. You can then pass these references just like any other scalar, and use them in the place of named handles. open my $fh, $file_name; open local $fh, $file_name; print $fh "Hello World!\n"; process_file( $fh ); If you like, you can store these filehandles in an array or a hash. If you access them directly, they aren't simple scalars and you need to give "print" a little help by placing the filehandle reference in braces. Perl can only figure it out on its own when the filehandle reference is a simple scalar. my @fhs = ( $fh1, $fh2, $fh3 ); for( $i = 0; $i <= $#fhs; $i++ ) { print {$fhs[$i]} "just another Perl answer, \n"; } Before perl5.6, you had to deal with various typeglob idioms which you may see in older code. open FILE, "> $filename"; process_typeglob( *FILE ); process_reference( \*FILE ); sub process_typeglob { local *FH = shift; print FH "Typeglob!" } sub process_reference { local $fh = shift; print $fh "Reference!" } If you want to create many anonymous handles, you should check out the Symbol or IO::Handle modules. Why do I get weird spaces when I print an array of lines? (contributed by brian d foy) If you are seeing spaces between the elements of your array when you print the array, you are probably interpolating the array in double quotes: my @animals = qw(camel llama alpaca vicuna); print "animals are: @animals\n"; It's the double quotes, not the "print", doing this. Whenever you interpolate an array in a double quote context, Perl joins the elements with spaces (or whatever is in $", which is a space by default): animals are: camel llama alpaca vicuna This is different than printing the array without the interpolation: my @animals = qw(camel llama alpaca vicuna); print "animals are: ", @animals, "\n"; Now the output doesn't have the spaces between the elements because the elements of @animals simply become part of the list to "print": animals are: camelllamaalpacavicuna You might notice this when each of the elements of @array end with a newline. You expect to print one element per line, but notice that every line after the first is indented: this is a line this is another line this is the third line That extra space comes from the interpolation of the array. If you don't want to put anything between your array elements, don't use the array in double quotes. You can send it to print without them: print @lines; Found in /usr/share/perl/5.34/pod/perlfaq7.pod How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}? You need to pass references to these objects. See "Pass by Reference" in perlsub for this particular question, and perlref for information on references. Passing Variables and Functions Regular variables and functions are quite easy to pass: just pass in a reference to an existing or anonymous variable or function: func( \$some_scalar ); func( \@some_array ); func( [ 1 .. 10 ] ); func( \%some_hash ); func( { this => 10, that => 20 } ); func( \&some_func ); func( sub { $_[0] ** $_[1] } ); Passing Filehandles As of Perl 5.6, you can represent filehandles with scalar variables which you treat as any other scalar. open my $fh, $filename or die "Cannot open $filename! $!"; func( $fh ); sub func { my $passed_fh = shift; my $line = <$passed_fh>; } Before Perl 5.6, you had to use the *FH or "\*FH" notations. These are "typeglobs"--see "Typeglobs and Filehandles" in perldata and especially "Pass by Reference" in perlsub for more information. Passing Regexes Here's an example of how to pass in a string and a regular expression for it to match against. You construct the pattern with the "qr//" operator: sub compare { my ($val1, $regex) = @_; my $retval = $val1 =~ /$regex/; return $retval; } $match = compare("old McDonald", qr/d.*D/i); Passing Methods To pass an object method into a subroutine, you can do this: call_a_lot(10, $some_obj, "methname") sub call_a_lot { my ($count, $widget, $trick) = @_; for (my $i = 0; $i < $count; $i++) { $widget->$trick(); } } Or, you can use a closure to bundle up the object, its method call, and arguments: my $whatnot = sub { $some_obj->obfuscate(@args) }; func($whatnot); sub func { my $code = shift; &$code(); } You could also investigate the can() method in the UNIVERSAL class (part of the standard perl distribution).
Generated by phpman v3.7.12 Author: Che Dong Under GNU General Public License
2026-06-14 05:38 @216.73.216.200
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)