3 perlfaq4 - Data Manipulation ($Revision: 1.15 $)
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", 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 charcters 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:
289 $line =~ s/\b(\w)/\U$1/g;
291 To make the whole line upper case:
294 To force each word to be lower case, with the first letter upper case:
295 $line =~ s/(\w+)/\u\L$1/g;
297 =head2 How can I split a [character] delimited string except when inside
298 [character]? (Comma-separated files)
300 Take the example case of trying to split a string that is comma-separated
301 into its different fields. (We'll pretend you said comma-separated, not
302 comma-delimited, which is different and almost never what you mean.) You
303 can't use C<split(/,/)> because you shouldn't split if the comma is inside
304 quotes. For example, take a data line like this:
306 SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"
308 Due to the restriction of the quotes, this is a fairly complex
309 problem. Thankfully, we have Jeffrey Friedl, author of a highly
310 recommended book on regular expressions, to handle these for us. He
311 suggests (assuming your string is contained in $text):
314 push(@new, $+) while $text =~ m{
315 "([^\"\\]*(?:\\.[^\"\\]*)*)",? # groups the phrase inside the quotes
319 push(@new, undef) if substr($text,-1,1) eq ',';
321 Alternatively, the Text::ParseWords module (part of the standard perl
322 distribution) lets you say:
324 use Text::ParseWords;
325 @new = quotewords(",", 0, $text);
327 =head2 How do I strip blank space from the beginning/end of a string?
329 The simplest approach, albeit not the fastest, is probably like this:
331 $string =~ s/^\s*(.*?)\s*$/$1/;
333 It would be faster to do this in two steps:
338 Or more nicely written as:
345 =head2 How do I extract selected columns from a string?
347 Use substr() or unpack(), both documented in L<perlfunc>.
349 =head2 How do I find the soundex value of a string?
351 Use the standard Text::Soundex module distributed with perl.
353 =head2 How can I expand variables in text strings?
355 Let's assume that you have a string like:
357 $text = 'this has a $foo in it and a $bar';
358 $text =~ s/\$(\w+)/${$1}/g;
360 Before version 5 of perl, this had to be done with a double-eval
363 $text =~ s/(\$\w+)/$1/eeg;
365 Which is bizarre enough that you'll probably actually need an EEG
368 =head2 What's wrong with always quoting "$vars"?
370 The problem is that those double-quotes force stringification,
371 coercing numbers and references into strings, even when you
372 don't want them to be.
374 If you get used to writing odd things like these:
378 somefunc("$var"); # BAD
380 You'll be in trouble. Those should (in 99.8% of the cases) be
381 the simpler and more direct:
387 Otherwise, besides slowing you down, you're going to break code when
388 the thing in the scalar is actually neither a string nor a number, but
394 my $oref = "$aref"; # WRONG
397 You can also get into subtle problems on those few operations in Perl
398 that actually do care about the difference between a string and a
399 number, such as the magical C<++> autoincrement operator or the
402 =head2 Why don't my <<HERE documents work?
404 Check for these three things:
408 =item 1. There must be no space after the << part.
410 =item 2. There (probably) should be a semicolon at the end.
412 =item 3. You can't (easily) have any space in front of the tag.
418 =head2 What is the difference between $array[1] and @array[1]?
420 The former is a scalar value, the latter an array slice, which makes
421 it a list with one (scalar) value. You should use $ when you want a
422 scalar value (most of the time) and @ when you want a list with one
423 scalar value in it (very, very rarely; nearly never, in fact).
425 Sometimes it doesn't make a difference, but sometimes it does.
426 For example, compare:
428 $good[0] = `some program that outputs several lines`;
432 @bad[0] = `same program that outputs several lines`;
434 The B<-w> flag will warn you about these matters.
436 =head2 How can I extract just the unique elements of an array?
438 There are several possible ways, depending on whether the array is
439 ordered and whether you wish to preserve the ordering.
443 =item a) If @in is sorted, and you want @out to be sorted:
446 @out = grep($_ ne $prev && ($prev = $_), @in);
448 This is nice in that it doesn't use much extra memory,
449 simulating uniq(1)'s behavior of removing only adjacent
452 =item b) If you don't know whether @in is sorted:
455 @out = grep(!$saw{$_}++, @in);
457 =item c) Like (b), but @in contains only small integers:
459 @out = grep(!$saw[$_]++, @in);
461 =item d) A way to do (b) without any loops or greps:
465 @out = sort keys %saw; # remove sort if undesired
467 =item e) Like (d), but @in contains only small positive integers:
475 =head2 How can I tell whether an array contains a certain element?
477 There are several ways to approach this. If you are going to make
478 this query many times and the values are arbitrary strings, the
479 fastest way is probably to invert the original array and keep an
480 associative array lying about whose keys are the first array's values.
482 @blues = qw/azure cerulean teal turquoise lapis-lazuli/;
484 for (@blues) { $is_blue{$_} = 1 }
486 Now you can check whether $is_blue{$some_color}. It might have been a
487 good idea to keep the blues all in a hash in the first place.
489 If the values are all small integers, you could use a simple indexed
490 array. This kind of an array will take up less space:
492 @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
493 undef @is_tiny_prime;
494 for (@primes) { $is_tiny_prime[$_] = 1; }
496 Now you check whether $is_tiny_prime[$some_number].
498 If the values in question are integers instead of strings, you can save
499 quite a lot of space by using bit strings instead:
501 @articles = ( 1..10, 150..2000, 2017 );
503 grep (vec($read,$_,1) = 1, @articles);
505 Now check whether C<vec($read,$n,1)> is true for some C<$n>.
509 $is_there = grep $_ eq $whatever, @array;
513 $is_there = grep /$whatever/, @array;
515 These are slow (checks every element even if the first matches),
516 inefficient (same reason), and potentially buggy (what if there are
517 regexp characters in $whatever?).
519 =head2 How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
521 Use a hash. Here's code to do both and more. It assumes that
522 each element is unique in a given array:
524 @union = @intersection = @difference = ();
526 foreach $element (@array1, @array2) { $count{$element}++ }
527 foreach $element (keys %count) {
528 push @union, $element;
529 push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
532 =head2 How do I find the first array element for which a condition is true?
534 You can use this if you care about the index:
536 for ($i=0; $i < @array; $i++) {
537 if ($array[$i] eq "Waldo") {
543 Now C<$found_index> has what you want.
545 =head2 How do I handle linked lists?
547 In general, you usually don't need a linked list in Perl, since with
548 regular arrays, you can push and pop or shift and unshift at either end,
549 or you can use splice to add and/or remove arbitrary number of elements
552 If you really, really wanted, you could use structures as described in
553 L<perldsc> or L<perltoot> and do just what the algorithm book tells you
556 =head2 How do I handle circular lists?
558 Circular lists could be handled in the traditional fashion with linked
559 lists, or you could just do something like this with an array:
561 unshift(@array, pop(@array)); # the last shall be first
562 push(@array, shift(@array)); # and vice versa
564 =head2 How do I shuffle an array randomly?
566 Here's a shuffling algorithm which works its way through the list,
567 randomly picking another element to swap the current element with:
571 @old = 1 .. 10; # just a demo
573 push(@new, splice(@old, rand @old, 1));
576 For large arrays, this avoids a lot of the reshuffling:
580 @old = 1 .. 10000; # just a demo
587 =head2 How do I process/modify each element of an array?
589 Use C<for>/C<foreach>:
596 Here's another; let's compute spherical volumes:
600 $_ *= (4/3) * 3.14159; # this will be constant folded
603 =head2 How do I select a random element from an array?
605 Use the rand() function (see L<perlfunc/rand>):
607 srand; # not needed for 5.004 and later
608 $index = rand @array;
609 $element = $array[$index];
611 =head2 How do I permute N elements of a list?
613 Here's a little program that generates all permutations
614 of all the words on each line of input. The algorithm embodied
615 in the permut() function should work on any list:
618 # permute - tchrist@perl.com
621 my @head = @{ $_[0] };
622 my @tail = @{ $_[1] };
624 # stop recursing when there are no elements in the head
627 # for all elements in @head, move one from @head to @tail
628 # and call permut() on the new @head and @tail
629 my(@newhead,@newtail,$i);
630 foreach $i (0 .. $#head) {
633 unshift(@newtail, splice(@newhead, $i, 1));
634 permut([@newhead], [@newtail]);
639 =head2 How do I sort an array by (anything)?
641 Supply a comparison function to sort() (described in L<perlfunc/sort>):
643 @list = sort { $a <=> $b } @list;
645 The default sort function is cmp, string comparison, which would
646 sort C<(1, 2, 10)> into C<(1, 10, 2)>. C<E<lt>=E<gt>>, used above, is
647 the numerical comparison operator.
649 If you have a complicated function needed to pull out the part you
650 want to sort on, then don't do it inside the sort function. Pull it
651 out first, because the sort BLOCK can be called many times for the
652 same element. Here's an example of how to pull out the first word
653 after the first number on each item, and then sort those words
658 ($item) = /\d+\s*(\S+)/;
659 push @idx, uc($item);
661 @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];
663 Which could also be written this way, using a trick
664 that's come to be known as the Schwartzian Transform:
666 @sorted = map { $_->[0] }
667 sort { $a->[1] cmp $b->[1] }
668 map { [ $_, uc((/\d+\s*(\S+) )[0] ] } @data;
670 If you need to sort on several fields, the following paradigm is useful.
672 @sorted = sort { field1($a) <=> field1($b) ||
673 field2($a) cmp field2($b) ||
674 field3($a) cmp field3($b)
677 This can be conveniently combined with precalculation of keys as given
680 See http://www.perl.com/CPAN/doc/FMTEYEWTK/sort.html for more about
683 See also the question below on sorting hashes.
685 =head2 How do I manipulate arrays of bits?
687 Use pack() and unpack(), or else vec() and the bitwise operations.
689 For example, this sets $vec to have bit N set if $ints[N] was set:
692 foreach(@ints) { vec($vec,$_,1) = 1 }
694 And here's how, given a vector in $vec, you can
695 get those bits into your @ints array:
700 # Find null-byte density then select best algorithm
701 if ($vec =~ tr/\0// / length $vec > 0.95) {
704 # This method is faster with mostly null-bytes
705 while($vec =~ /[^\0]/g ) {
706 $i = -9 + 8 * pos $vec;
707 push @ints, $i if vec($vec, ++$i, 1);
708 push @ints, $i if vec($vec, ++$i, 1);
709 push @ints, $i if vec($vec, ++$i, 1);
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);
717 # This method is a fast general algorithm
719 my $bits = unpack "b*", $vec;
720 push @ints, 0 if $bits =~ s/^(\d)// && $1;
721 push @ints, pos $bits while($bits =~ /1/g);
726 This method gets faster the more sparse the bit vector is.
727 (Courtesy of Tim Bunce and Winfried Koenig.)
729 =head2 Why does defined() return true on empty arrays and hashes?
731 See L<perlfunc/defined> in the 5.004 release or later of Perl.
733 =head1 Data: Hashes (Associative Arrays)
735 =head2 How do I process an entire hash?
737 Use the each() function (see L<perlfunc/each>) if you don't care
740 while (($key,$value) = each %hash) {
741 print "$key = $value\n";
744 If you want it sorted, you'll have to use foreach() on the result of
745 sorting the keys as shown in an earlier question.
747 =head2 What happens if I add or remove keys from a hash while iterating over it?
751 =head2 How do I look up a hash element by value?
753 Create a reverse hash:
755 %by_value = reverse %by_key;
756 $key = $by_value{$value};
758 That's not particularly efficient. It would be more space-efficient
761 while (($key, $value) = each %by_key) {
762 $by_value{$value} = $key;
765 If your hash could have repeated values, the methods above will only
766 find one of the associated keys. This may or may not worry you.
768 =head2 How can I know how many entries are in a hash?
770 If you mean how many keys, then all you have to do is
771 take the scalar sense of the keys() function:
773 $num_keys = scalar keys %hash;
775 In void context it just resets the iterator, which is faster
778 =head2 How do I sort a hash (optionally by value instead of key)?
780 Internally, hashes are stored in a way that prevents you from imposing
781 an order on key-value pairs. Instead, you have to sort a list of the
784 @keys = sort keys %hash; # sorted by key
786 $hash{$a} cmp $hash{$b}
787 } keys %hash; # and by value
789 Here we'll do a reverse numeric sort by value, and if two keys are
790 identical, sort by length of key, and if that fails, by straight ASCII
791 comparison of the keys (well, possibly modified by your locale -- see
795 $hash{$b} <=> $hash{$a}
797 length($b) <=> length($a)
802 =head2 How can I always keep my hash sorted?
804 You can look into using the DB_File module and tie() using the
805 $DB_BTREE hash bindings as documented in L<DB_File/"In Memory Databases">.
807 =head2 What's the difference between "delete" and "undef" with hashes?
809 Hashes are pairs of scalars: the first is the key, the second is the
810 value. The key will be coerced to a string, although the value can be
811 any kind of scalar: string, number, or reference. If a key C<$key> is
812 present in the array, C<exists($key)> will return true. The value for
813 a given key can be C<undef>, in which case C<$array{$key}> will be
814 C<undef> while C<$exists{$key}> will return true. This corresponds to
815 (C<$key>, C<undef>) being in the hash.
817 Pictures help... here's the C<%ary> table:
827 And these conditions hold
831 defined $ary{'d'} is true
832 defined $ary{'a'} is true
833 exists $ary{'a'} is true (perl5 only)
834 grep ($_ eq 'a', keys %ary) is true
840 your table now reads:
851 and these conditions now hold; changes in caps:
855 defined $ary{'d'} is true
856 defined $ary{'a'} is FALSE
857 exists $ary{'a'} is true (perl5 only)
858 grep ($_ eq 'a', keys %ary) is true
860 Notice the last two: you have an undef value, but a defined key!
866 your table now reads:
875 and these conditions now hold; changes in caps:
879 defined $ary{'d'} is true
880 defined $ary{'a'} is false
881 exists $ary{'a'} is FALSE (perl5 only)
882 grep ($_ eq 'a', keys %ary) is FALSE
884 See, the whole entry is gone!
886 =head2 Why don't my tied hashes make the defined/exists distinction?
888 They may or may not implement the EXISTS() and DEFINED() methods
889 differently. For example, there isn't the concept of undef with hashes
890 that are tied to DBM* files. This means the true/false tables above
891 will give different results when used on such a hash. It also means
892 that exists and defined do the same thing with a DBM* file, and what
893 they end up doing is not what they do with ordinary hashes.
895 =head2 How do I reset an each() operation part-way through?
897 Using C<keys %hash> in a scalar context returns the number of keys in
898 the hash I<and> resets the iterator associated with the hash. You may
899 need to do this if you use C<last> to exit a loop early so that when you
900 re-enter it, the hash iterator has been reset.
902 =head2 How can I get the unique keys from two hashes?
904 First you extract the keys from the hashes into arrays, and then solve
905 the uniquifying the array problem described above. For example:
908 for $element (keys(%foo), keys(%bar)) {
915 @uniq = keys %{{%foo,%bar}};
917 Or if you really want to save space:
920 while (defined ($key = each %foo)) {
923 while (defined ($key = each %bar)) {
928 =head2 How can I store a multidimensional array in a DBM file?
930 Either stringify the structure yourself (no fun), or else
931 get the MLDBM (which uses Data::Dumper) module from CPAN and layer
932 it on top of either DB_File or GDBM_File.
934 =head2 How can I make my hash remember the order I put elements into it?
936 Use the Tie::IxHash from CPAN.
938 =head2 Why does passing a subroutine an undefined element in a hash create it?
940 If you say something like:
942 somefunc($hash{"nonesuch key here"});
944 Then that element "autovivifies"; that is, it springs into existence
945 whether you store something there or not. That's because functions
946 get scalars passed in by reference. If somefunc() modifies C<$_[0]>,
947 it has to be ready to write it back into the caller's version.
949 This has been fixed as of perl5.004.
951 Normally, merely accessing a key's value for a nonexistent key does
952 I<not> cause that key to be forever there. This is different than
955 =head2 How can I make the Perl equivalent of a C structure/C++ class/hash
956 or array of hashes or arrays?
958 Use references (documented in L<perlref>). Examples of complex data
959 structures are given in L<perldsc> and L<perllol>. Examples of
960 structures and object-oriented classes are in L<perltoot>.
962 =head2 How can I use a reference as a hash key?
964 You can't do this directly, but you could use the standard Tie::Refhash
965 module distributed with perl.
969 =head2 How do I handle binary data correctly?
971 Perl is binary clean, so this shouldn't be a problem. For example,
972 this works fine (assuming the files are found):
974 if (`cat /vmunix` =~ /gzip/) {
975 print "Your kernel is GNU-zip enabled!\n";
978 On some systems, however, you have to play tedious games with "text"
979 versus "binary" files. See L<perlfunc/"binmode">.
981 If you're concerned about 8-bit ASCII data, then see L<perllocale>.
983 If you want to deal with multi-byte characters, however, there are
984 some gotchas. See the section on Regular Expressions.
986 =head2 How do I determine whether a scalar is a number/whole/integer/float?
988 Assuming that you don't care about IEEE notations like "NaN" or
989 "Infinity", you probably just want to use a regular expression.
991 warn "has nondigits" if /\D/;
992 warn "not a whole number" unless /^\d+$/;
993 warn "not an integer" unless /^-?\d+$/; # reject +3
994 warn "not an integer" unless /^[+-]?\d+$/;
995 warn "not a decimal number" unless /^-?\d+\.?\d*$/; # rejects .2
996 warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
998 unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
1000 Or you could check out
1001 http://www.perl.com/CPAN/modules/by-module/String/String-Scanf-1.1.tar.gz
1002 instead. The POSIX module (part of the standard Perl distribution)
1003 provides the C<strtol> and C<strtod> for converting strings to double
1004 and longs, respectively.
1006 =head2 How do I keep persistent data across program calls?
1008 For some specific applications, you can use one of the DBM modules.
1009 See L<AnyDBM_File>. More generically, you should consult the
1010 FreezeThaw, Storable, or Class::Eroot modules from CPAN.
1012 =head2 How do I print out or copy a recursive data structure?
1014 The Data::Dumper module on CPAN is nice for printing out
1015 data structures, and FreezeThaw for copying them. For example:
1017 use FreezeThaw qw(freeze thaw);
1018 $new = thaw freeze $old;
1020 Where $old can be (a reference to) any kind of data structure you'd like.
1021 It will be deeply copied.
1023 =head2 How do I define methods for every class/object?
1025 Use the UNIVERSAL class (see L<UNIVERSAL>).
1027 =head2 How do I verify a credit card checksum?
1029 Get the Business::CreditCard module from CPAN.
1031 =head1 AUTHOR AND COPYRIGHT
1033 Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
1034 All rights reserved. See L<perlfaq> for distribution information.