3 perlfaq4 - Data Manipulation ($Revision: 1.17 $, $Date: 1997/03/25 18:16:24 $)
7 The section of the FAQ answers question related to the manipulation
8 of data as numbers, dates, strings, arrays, hashes, and miscellaneous
13 =head2 Why isn't my octal data interpreted correctly?
15 Perl only understands octal and hex numbers as such when they occur
16 as literals in your program. If they are read in from somewhere and
17 assigned, no automatic conversion takes place. You must explicitly
18 use oct() or hex() if you want the values converted. oct() interprets
19 both hex ("0x350") numbers and octal ones ("0350" or even without the
20 leading "0", like "377"), while hex() only converts hexadecimal ones,
21 with or without a leading "0x", like "0x255", "3A", "ff", or "deadbeef".
23 This problem shows up most often when people try using chmod(), mkdir(),
24 umask(), or sysopen(), which all want permissions in octal.
26 chmod(644, $file); # WRONG -- perl -w catches this
27 chmod(0644, $file); # right
29 =head2 Does perl have a round function? What about ceil() and floor()?
32 For rounding to a certain number of digits, sprintf() or printf() is
33 usually the easiest route.
35 The POSIX module (part of the standard perl distribution) implements
36 ceil(), floor(), and a number of other mathematical and trigonometric
39 The Math::Complex module (part of the standard perl distribution)
40 defines a number of mathematical functions that can also work on real
41 numbers. It's not as efficient as the POSIX library, but the POSIX
42 library can't work with complex numbers.
44 Rounding in financial applications can have serious implications, and
45 the rounding method used should be specified precisely. In these
46 cases, it probably pays not to trust whichever system rounding is
47 being used by Perl, but to instead implement the rounding function you
50 =head2 How do I convert bits into ints?
52 To turn a string of 1s and 0s like '10110110' into a scalar containing
53 its binary value, use the pack() function (documented in
56 $decimal = pack('B8', '10110110');
58 Here's an example of going the other way:
60 $binary_string = join('', unpack('B*', "\x29"));
62 =head2 How do I multiply matrices?
64 Use the Math::Matrix or Math::MatrixReal modules (available from CPAN)
65 or the PDL extension (also available from CPAN).
67 =head2 How do I perform an operation on a series of integers?
69 To call a function on each element in an array, and collect the
72 @results = map { my_func($_) } @array;
76 @triple = map { 3 * $_ } @single;
78 To call a function on each element of an array, but ignore the
81 foreach $iterator (@array) {
85 To call a function on each integer in a (small) range, you B<can> use:
87 @results = map { &my_func($_) } (5 .. 25);
89 but you should be aware that the C<..> operator creates an array of
90 all integers in the range. This can take a lot of memory for large
94 for ($i=5; $i < 500_005; $i++) {
95 push(@results, &my_func($i));
98 =head2 How can I output Roman numerals?
100 Get the http://www.perl.com/CPAN/modules/by-module/Roman module.
102 =head2 Why aren't my random numbers random?
104 The short explanation is that you're getting pseudorandom numbers, not
105 random ones, because that's how these things work. A longer
106 explanation is available on
107 http://www.perl.com/CPAN/doc/FMTEYEWTK/random, courtesy of Tom
110 You should also check out the Math::TrulyRandom module from CPAN.
114 =head2 How do I find the week-of-the-year/day-of-the-year?
116 The day of the year is in the array returned by localtime() (see
117 L<perlfunc/"localtime">):
119 $day_of_year = (localtime(time()))[7];
121 or more legibly (in 5.004 or higher):
124 $day_of_year = localtime(time())->yday;
126 You can find the week of the year by dividing this by 7:
128 $week_of_year = int($day_of_year / 7);
130 Of course, this believes that weeks start at zero.
132 =head2 How can I compare two date strings?
134 Use the Date::Manip or Date::DateCalc modules from CPAN.
136 =head2 How can I take a string and turn it into epoch seconds?
138 If it's a regular enough string that it always has the same format,
139 you can split it up and pass the parts to timelocal in the standard
140 Time::Local module. Otherwise, you should look into one of the
141 Date modules from CPAN.
143 =head2 How can I find the Julian Day?
145 Neither Date::Manip nor Date::DateCalc deal with Julian days.
146 Instead, there is an example of Julian date calculation in
147 http://www.perl.com/CPAN/authors/David_Muir_Sharnoff/modules/Time/JulianDay.pm.gz,
150 =head2 Does Perl have a year 2000 problem?
152 Not unless you use Perl to create one. The date and time functions
153 supplied with perl (gmtime and localtime) supply adequate information
154 to determine the year well beyond 2000 (2038 is when trouble strikes).
155 The year returned by these functions when used in an array context is
156 the year minus 1900. For years between 1910 and 1999 this I<happens>
157 to be a 2-digit decimal number. To avoid the year 2000 problem simply
158 do not treat the year as a 2-digit number. It isn't.
160 When gmtime() and localtime() are used in a scalar context they return
161 a timestamp string that contains a fully-expanded year. For example,
162 C<$timestamp = gmtime(1005613200)> sets $timestamp to "Tue Nov 13 01:00:00
163 2001". There's no year 2000 problem here.
167 =head2 How do I validate input?
169 The answer to this question is usually a regular expression, perhaps
170 with auxiliary logic. See the more specific questions (numbers, email
171 addresses, etc.) for details.
173 =head2 How do I unescape a string?
175 It depends just what you mean by "escape". URL escapes are dealt with
176 in L<perlfaq9>. Shell escapes with the backslash (\)
177 character are removed with:
181 Note that this won't expand \n or \t or any other special escapes.
183 =head2 How do I remove consecutive pairs of characters?
185 To turn "abbcccd" into "abccd":
189 =head2 How do I expand function calls in a string?
191 This is documented in L<perlref>. In general, this is fraught with
192 quoting and readability problems, but it is possible. To interpolate
193 a subroutine call (in a list context) into a string:
195 print "My sub returned @{[mysub(1,2,3)]} that time.\n";
197 If you prefer scalar context, similar chicanery is also useful for
198 arbitrary expressions:
200 print "That yields ${\($n + 5)} widgets\n";
202 =head2 How do I find matching/nesting anything?
204 This isn't something that can be tackled in one regular expression, no
205 matter how complicated. To find something between two single characters,
206 a pattern like C</x([^x]*)x/> will get the intervening bits in $1. For
207 multiple ones, then something more like C</alpha(.*?)omega/> would
208 be needed. But none of these deals with nested patterns, nor can they.
209 For that you'll have to write a parser.
211 =head2 How do I reverse a string?
213 Use reverse() in a scalar context, as documented in
216 $reversed = reverse $string;
218 =head2 How do I expand tabs in a string?
220 You can do it the old-fashioned way:
222 1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
224 Or you can just use the Text::Tabs module (part of the standard perl
228 @expanded_lines = expand(@lines_with_tabs);
230 =head2 How do I reformat a paragraph?
232 Use Text::Wrap (part of the standard perl distribution):
235 print wrap("\t", ' ', @paragraphs);
237 =head2 How can I access/change the first N letters of a string?
239 There are many ways. If you just want to grab a copy, use
242 $first_byte = substr($a, 0, 1);
244 If you want to modify part of a string, the simplest way is often to
245 use substr() as an lvalue:
247 substr($a, 0, 3) = "Tom";
249 Although those with a regexp kind of thought process will likely prefer
253 =head2 How do I change the Nth occurrence of something?
255 You have to keep track. For example, let's say you want
256 to change the fifth occurrence of "whoever" or "whomever"
257 into "whosoever" or "whomsoever", case insensitively.
261 ++$count == 5 # is it the 5th?
262 ? "${2}soever" # yes, swap
263 : $1 # renege and leave it there
266 =head2 How can I count the number of occurrences of a substring within a string?
268 There are a number of ways, with varying efficiency: If you want a
269 count of a certain single character (X) within a string, you can use the
270 C<tr///> function like so:
272 $string = "ThisXlineXhasXsomeXx'sXinXit":
273 $count = ($string =~ tr/X//);
274 print "There are $count X characters in the string";
276 This is fine if you are just looking for a single character. However,
277 if you are trying to count multiple character substrings within a
278 larger string, C<tr///> won't work. What you can do is wrap a while()
279 loop around a global pattern match. For example, let's count negative
282 $string = "-9 55 48 -2 23 -76 4 14 -44";
283 while ($string =~ /-\d+/g) { $count++ }
284 print "There are $count negative numbers in the string";
286 =head2 How do I capitalize all the words on one line?
288 To make the first letter of each word upper case:
290 $line =~ s/\b(\w)/\U$1/g;
292 To make the whole line upper case:
296 To force each word to be lower case, with the first letter upper case:
298 $line =~ s/(\w+)/\u\L$1/g;
300 =head2 How can I split a [character] delimited string except when inside
301 [character]? (Comma-separated files)
303 Take the example case of trying to split a string that is comma-separated
304 into its different fields. (We'll pretend you said comma-separated, not
305 comma-delimited, which is different and almost never what you mean.) You
306 can't use C<split(/,/)> because you shouldn't split if the comma is inside
307 quotes. For example, take a data line like this:
309 SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"
311 Due to the restriction of the quotes, this is a fairly complex
312 problem. Thankfully, we have Jeffrey Friedl, author of a highly
313 recommended book on regular expressions, to handle these for us. He
314 suggests (assuming your string is contained in $text):
317 push(@new, $+) while $text =~ m{
318 "([^\"\\]*(?:\\.[^\"\\]*)*)",? # groups the phrase inside the quotes
322 push(@new, undef) if substr($text,-1,1) eq ',';
324 Alternatively, the Text::ParseWords module (part of the standard perl
325 distribution) lets you say:
327 use Text::ParseWords;
328 @new = quotewords(",", 0, $text);
330 =head2 How do I strip blank space from the beginning/end of a string?
332 The simplest approach, albeit not the fastest, is probably like this:
334 $string =~ s/^\s*(.*?)\s*$/$1/;
336 It would be faster to do this in two steps:
341 Or more nicely written as:
348 =head2 How do I extract selected columns from a string?
350 Use substr() or unpack(), both documented in L<perlfunc>.
352 =head2 How do I find the soundex value of a string?
354 Use the standard Text::Soundex module distributed with perl.
356 =head2 How can I expand variables in text strings?
358 Let's assume that you have a string like:
360 $text = 'this has a $foo in it and a $bar';
361 $text =~ s/\$(\w+)/${$1}/g;
363 Before version 5 of perl, this had to be done with a double-eval
366 $text =~ s/(\$\w+)/$1/eeg;
368 Which is bizarre enough that you'll probably actually need an EEG
371 =head2 What's wrong with always quoting "$vars"?
373 The problem is that those double-quotes force stringification,
374 coercing numbers and references into strings, even when you
375 don't want them to be.
377 If you get used to writing odd things like these:
381 somefunc("$var"); # BAD
383 You'll be in trouble. Those should (in 99.8% of the cases) be
384 the simpler and more direct:
390 Otherwise, besides slowing you down, you're going to break code when
391 the thing in the scalar is actually neither a string nor a number, but
397 my $oref = "$aref"; # WRONG
400 You can also get into subtle problems on those few operations in Perl
401 that actually do care about the difference between a string and a
402 number, such as the magical C<++> autoincrement operator or the
405 =head2 Why don't my <<HERE documents work?
407 Check for these three things:
411 =item 1. There must be no space after the << part.
413 =item 2. There (probably) should be a semicolon at the end.
415 =item 3. You can't (easily) have any space in front of the tag.
421 =head2 What is the difference between $array[1] and @array[1]?
423 The former is a scalar value, the latter an array slice, which makes
424 it a list with one (scalar) value. You should use $ when you want a
425 scalar value (most of the time) and @ when you want a list with one
426 scalar value in it (very, very rarely; nearly never, in fact).
428 Sometimes it doesn't make a difference, but sometimes it does.
429 For example, compare:
431 $good[0] = `some program that outputs several lines`;
435 @bad[0] = `same program that outputs several lines`;
437 The B<-w> flag will warn you about these matters.
439 =head2 How can I extract just the unique elements of an array?
441 There are several possible ways, depending on whether the array is
442 ordered and whether you wish to preserve the ordering.
446 =item a) If @in is sorted, and you want @out to be sorted:
449 @out = grep($_ ne $prev && ($prev = $_), @in);
451 This is nice in that it doesn't use much extra memory,
452 simulating uniq(1)'s behavior of removing only adjacent
455 =item b) If you don't know whether @in is sorted:
458 @out = grep(!$saw{$_}++, @in);
460 =item c) Like (b), but @in contains only small integers:
462 @out = grep(!$saw[$_]++, @in);
464 =item d) A way to do (b) without any loops or greps:
468 @out = sort keys %saw; # remove sort if undesired
470 =item e) Like (d), but @in contains only small positive integers:
478 =head2 How can I tell whether an array contains a certain element?
480 There are several ways to approach this. If you are going to make
481 this query many times and the values are arbitrary strings, the
482 fastest way is probably to invert the original array and keep an
483 associative array lying about whose keys are the first array's values.
485 @blues = qw/azure cerulean teal turquoise lapis-lazuli/;
487 for (@blues) { $is_blue{$_} = 1 }
489 Now you can check whether $is_blue{$some_color}. It might have been a
490 good idea to keep the blues all in a hash in the first place.
492 If the values are all small integers, you could use a simple indexed
493 array. This kind of an array will take up less space:
495 @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
496 undef @is_tiny_prime;
497 for (@primes) { $is_tiny_prime[$_] = 1; }
499 Now you check whether $is_tiny_prime[$some_number].
501 If the values in question are integers instead of strings, you can save
502 quite a lot of space by using bit strings instead:
504 @articles = ( 1..10, 150..2000, 2017 );
506 grep (vec($read,$_,1) = 1, @articles);
508 Now check whether C<vec($read,$n,1)> is true for some C<$n>.
512 $is_there = grep $_ eq $whatever, @array;
516 $is_there = grep /$whatever/, @array;
518 These are slow (checks every element even if the first matches),
519 inefficient (same reason), and potentially buggy (what if there are
520 regexp characters in $whatever?).
522 =head2 How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
524 Use a hash. Here's code to do both and more. It assumes that
525 each element is unique in a given array:
527 @union = @intersection = @difference = ();
529 foreach $element (@array1, @array2) { $count{$element}++ }
530 foreach $element (keys %count) {
531 push @union, $element;
532 push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
535 =head2 How do I find the first array element for which a condition is true?
537 You can use this if you care about the index:
539 for ($i=0; $i < @array; $i++) {
540 if ($array[$i] eq "Waldo") {
546 Now C<$found_index> has what you want.
548 =head2 How do I handle linked lists?
550 In general, you usually don't need a linked list in Perl, since with
551 regular arrays, you can push and pop or shift and unshift at either end,
552 or you can use splice to add and/or remove arbitrary number of elements
555 If you really, really wanted, you could use structures as described in
556 L<perldsc> or L<perltoot> and do just what the algorithm book tells you
559 =head2 How do I handle circular lists?
561 Circular lists could be handled in the traditional fashion with linked
562 lists, or you could just do something like this with an array:
564 unshift(@array, pop(@array)); # the last shall be first
565 push(@array, shift(@array)); # and vice versa
567 =head2 How do I shuffle an array randomly?
569 Here's a shuffling algorithm which works its way through the list,
570 randomly picking another element to swap the current element with:
574 @old = 1 .. 10; # just a demo
576 push(@new, splice(@old, rand @old, 1));
579 For large arrays, this avoids a lot of the reshuffling:
583 @old = 1 .. 10000; # just a demo
590 =head2 How do I process/modify each element of an array?
592 Use C<for>/C<foreach>:
599 Here's another; let's compute spherical volumes:
603 $_ *= (4/3) * 3.14159; # this will be constant folded
606 =head2 How do I select a random element from an array?
608 Use the rand() function (see L<perlfunc/rand>):
610 srand; # not needed for 5.004 and later
611 $index = rand @array;
612 $element = $array[$index];
614 =head2 How do I permute N elements of a list?
616 Here's a little program that generates all permutations
617 of all the words on each line of input. The algorithm embodied
618 in the permut() function should work on any list:
621 # permute - tchrist@perl.com
624 my @head = @{ $_[0] };
625 my @tail = @{ $_[1] };
627 # stop recursing when there are no elements in the head
630 # for all elements in @head, move one from @head to @tail
631 # and call permut() on the new @head and @tail
632 my(@newhead,@newtail,$i);
633 foreach $i (0 .. $#head) {
636 unshift(@newtail, splice(@newhead, $i, 1));
637 permut([@newhead], [@newtail]);
642 =head2 How do I sort an array by (anything)?
644 Supply a comparison function to sort() (described in L<perlfunc/sort>):
646 @list = sort { $a <=> $b } @list;
648 The default sort function is cmp, string comparison, which would
649 sort C<(1, 2, 10)> into C<(1, 10, 2)>. C<E<lt>=E<gt>>, used above, is
650 the numerical comparison operator.
652 If you have a complicated function needed to pull out the part you
653 want to sort on, then don't do it inside the sort function. Pull it
654 out first, because the sort BLOCK can be called many times for the
655 same element. Here's an example of how to pull out the first word
656 after the first number on each item, and then sort those words
661 ($item) = /\d+\s*(\S+)/;
662 push @idx, uc($item);
664 @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];
666 Which could also be written this way, using a trick
667 that's come to be known as the Schwartzian Transform:
669 @sorted = map { $_->[0] }
670 sort { $a->[1] cmp $b->[1] }
671 map { [ $_, uc((/\d+\s*(\S+) )[0] ] } @data;
673 If you need to sort on several fields, the following paradigm is useful.
675 @sorted = sort { field1($a) <=> field1($b) ||
676 field2($a) cmp field2($b) ||
677 field3($a) cmp field3($b)
680 This can be conveniently combined with precalculation of keys as given
683 See http://www.perl.com/CPAN/doc/FMTEYEWTK/sort.html for more about
686 See also the question below on sorting hashes.
688 =head2 How do I manipulate arrays of bits?
690 Use pack() and unpack(), or else vec() and the bitwise operations.
692 For example, this sets $vec to have bit N set if $ints[N] was set:
695 foreach(@ints) { vec($vec,$_,1) = 1 }
697 And here's how, given a vector in $vec, you can
698 get those bits into your @ints array:
703 # Find null-byte density then select best algorithm
704 if ($vec =~ tr/\0// / length $vec > 0.95) {
707 # This method is faster with mostly null-bytes
708 while($vec =~ /[^\0]/g ) {
709 $i = -9 + 8 * pos $vec;
710 push @ints, $i if vec($vec, ++$i, 1);
711 push @ints, $i if vec($vec, ++$i, 1);
712 push @ints, $i if vec($vec, ++$i, 1);
713 push @ints, $i if vec($vec, ++$i, 1);
714 push @ints, $i if vec($vec, ++$i, 1);
715 push @ints, $i if vec($vec, ++$i, 1);
716 push @ints, $i if vec($vec, ++$i, 1);
717 push @ints, $i if vec($vec, ++$i, 1);
720 # This method is a fast general algorithm
722 my $bits = unpack "b*", $vec;
723 push @ints, 0 if $bits =~ s/^(\d)// && $1;
724 push @ints, pos $bits while($bits =~ /1/g);
729 This method gets faster the more sparse the bit vector is.
730 (Courtesy of Tim Bunce and Winfried Koenig.)
732 =head2 Why does defined() return true on empty arrays and hashes?
734 See L<perlfunc/defined> in the 5.004 release or later of Perl.
736 =head1 Data: Hashes (Associative Arrays)
738 =head2 How do I process an entire hash?
740 Use the each() function (see L<perlfunc/each>) if you don't care
743 while (($key,$value) = each %hash) {
744 print "$key = $value\n";
747 If you want it sorted, you'll have to use foreach() on the result of
748 sorting the keys as shown in an earlier question.
750 =head2 What happens if I add or remove keys from a hash while iterating over it?
754 =head2 How do I look up a hash element by value?
756 Create a reverse hash:
758 %by_value = reverse %by_key;
759 $key = $by_value{$value};
761 That's not particularly efficient. It would be more space-efficient
764 while (($key, $value) = each %by_key) {
765 $by_value{$value} = $key;
768 If your hash could have repeated values, the methods above will only
769 find one of the associated keys. This may or may not worry you.
771 =head2 How can I know how many entries are in a hash?
773 If you mean how many keys, then all you have to do is
774 take the scalar sense of the keys() function:
776 $num_keys = scalar keys %hash;
778 In void context it just resets the iterator, which is faster
781 =head2 How do I sort a hash (optionally by value instead of key)?
783 Internally, hashes are stored in a way that prevents you from imposing
784 an order on key-value pairs. Instead, you have to sort a list of the
787 @keys = sort keys %hash; # sorted by key
789 $hash{$a} cmp $hash{$b}
790 } keys %hash; # and by value
792 Here we'll do a reverse numeric sort by value, and if two keys are
793 identical, sort by length of key, and if that fails, by straight ASCII
794 comparison of the keys (well, possibly modified by your locale -- see
798 $hash{$b} <=> $hash{$a}
800 length($b) <=> length($a)
805 =head2 How can I always keep my hash sorted?
807 You can look into using the DB_File module and tie() using the
808 $DB_BTREE hash bindings as documented in L<DB_File/"In Memory Databases">.
810 =head2 What's the difference between "delete" and "undef" with hashes?
812 Hashes are pairs of scalars: the first is the key, the second is the
813 value. The key will be coerced to a string, although the value can be
814 any kind of scalar: string, number, or reference. If a key C<$key> is
815 present in the array, C<exists($key)> will return true. The value for
816 a given key can be C<undef>, in which case C<$array{$key}> will be
817 C<undef> while C<$exists{$key}> will return true. This corresponds to
818 (C<$key>, C<undef>) being in the hash.
820 Pictures help... here's the C<%ary> table:
830 And these conditions hold
834 defined $ary{'d'} is true
835 defined $ary{'a'} is true
836 exists $ary{'a'} is true (perl5 only)
837 grep ($_ eq 'a', keys %ary) is true
843 your table now reads:
854 and these conditions now hold; changes in caps:
858 defined $ary{'d'} is true
859 defined $ary{'a'} is FALSE
860 exists $ary{'a'} is true (perl5 only)
861 grep ($_ eq 'a', keys %ary) is true
863 Notice the last two: you have an undef value, but a defined key!
869 your table now reads:
878 and these conditions now hold; changes in caps:
882 defined $ary{'d'} is true
883 defined $ary{'a'} is false
884 exists $ary{'a'} is FALSE (perl5 only)
885 grep ($_ eq 'a', keys %ary) is FALSE
887 See, the whole entry is gone!
889 =head2 Why don't my tied hashes make the defined/exists distinction?
891 They may or may not implement the EXISTS() and DEFINED() methods
892 differently. For example, there isn't the concept of undef with hashes
893 that are tied to DBM* files. This means the true/false tables above
894 will give different results when used on such a hash. It also means
895 that exists and defined do the same thing with a DBM* file, and what
896 they end up doing is not what they do with ordinary hashes.
898 =head2 How do I reset an each() operation part-way through?
900 Using C<keys %hash> in a scalar context returns the number of keys in
901 the hash I<and> resets the iterator associated with the hash. You may
902 need to do this if you use C<last> to exit a loop early so that when you
903 reenter it, the hash iterator has been reset.
905 =head2 How can I get the unique keys from two hashes?
907 First you extract the keys from the hashes into arrays, and then solve
908 the uniquifying the array problem described above. For example:
911 for $element (keys(%foo), keys(%bar)) {
918 @uniq = keys %{{%foo,%bar}};
920 Or if you really want to save space:
923 while (defined ($key = each %foo)) {
926 while (defined ($key = each %bar)) {
931 =head2 How can I store a multidimensional array in a DBM file?
933 Either stringify the structure yourself (no fun), or else
934 get the MLDBM (which uses Data::Dumper) module from CPAN and layer
935 it on top of either DB_File or GDBM_File.
937 =head2 How can I make my hash remember the order I put elements into it?
939 Use the Tie::IxHash from CPAN.
941 =head2 Why does passing a subroutine an undefined element in a hash create it?
943 If you say something like:
945 somefunc($hash{"nonesuch key here"});
947 Then that element "autovivifies"; that is, it springs into existence
948 whether you store something there or not. That's because functions
949 get scalars passed in by reference. If somefunc() modifies C<$_[0]>,
950 it has to be ready to write it back into the caller's version.
952 This has been fixed as of perl5.004.
954 Normally, merely accessing a key's value for a nonexistent key does
955 I<not> cause that key to be forever there. This is different than
958 =head2 How can I make the Perl equivalent of a C structure/C++ class/hash
959 or array of hashes or arrays?
961 Use references (documented in L<perlref>). Examples of complex data
962 structures are given in L<perldsc> and L<perllol>. Examples of
963 structures and object-oriented classes are in L<perltoot>.
965 =head2 How can I use a reference as a hash key?
967 You can't do this directly, but you could use the standard Tie::Refhash
968 module distributed with perl.
972 =head2 How do I handle binary data correctly?
974 Perl is binary clean, so this shouldn't be a problem. For example,
975 this works fine (assuming the files are found):
977 if (`cat /vmunix` =~ /gzip/) {
978 print "Your kernel is GNU-zip enabled!\n";
981 On some systems, however, you have to play tedious games with "text"
982 versus "binary" files. See L<perlfunc/"binmode">.
984 If you're concerned about 8-bit ASCII data, then see L<perllocale>.
986 If you want to deal with multibyte characters, however, there are
987 some gotchas. See the section on Regular Expressions.
989 =head2 How do I determine whether a scalar is a number/whole/integer/float?
991 Assuming that you don't care about IEEE notations like "NaN" or
992 "Infinity", you probably just want to use a regular expression.
994 warn "has nondigits" if /\D/;
995 warn "not a whole number" unless /^\d+$/;
996 warn "not an integer" unless /^-?\d+$/; # reject +3
997 warn "not an integer" unless /^[+-]?\d+$/;
998 warn "not a decimal number" unless /^-?\d+\.?\d*$/; # rejects .2
999 warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
1000 warn "not a C float"
1001 unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
1003 Or you could check out
1004 http://www.perl.com/CPAN/modules/by-module/String/String-Scanf-1.1.tar.gz
1005 instead. The POSIX module (part of the standard Perl distribution)
1006 provides the C<strtol> and C<strtod> for converting strings to double
1007 and longs, respectively.
1009 =head2 How do I keep persistent data across program calls?
1011 For some specific applications, you can use one of the DBM modules.
1012 See L<AnyDBM_File>. More generically, you should consult the
1013 FreezeThaw, Storable, or Class::Eroot modules from CPAN.
1015 =head2 How do I print out or copy a recursive data structure?
1017 The Data::Dumper module on CPAN is nice for printing out
1018 data structures, and FreezeThaw for copying them. For example:
1020 use FreezeThaw qw(freeze thaw);
1021 $new = thaw freeze $old;
1023 Where $old can be (a reference to) any kind of data structure you'd like.
1024 It will be deeply copied.
1026 =head2 How do I define methods for every class/object?
1028 Use the UNIVERSAL class (see L<UNIVERSAL>).
1030 =head2 How do I verify a credit card checksum?
1032 Get the Business::CreditCard module from CPAN.
1034 =head1 AUTHOR AND COPYRIGHT
1036 Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
1037 All rights reserved. See L<perlfaq> for distribution information.