[inseparable changes from match from perl-5.003_93 to perl-5.003_94]
[p5sagit/p5-mst-13.2.git] / pod / perlfaq4.pod
1 =head1 NAME
2
3 perlfaq4 - Data Manipulation ($Revision: 1.15 $)
4
5 =head1 DESCRIPTION
6
7 The section of the FAQ answers question related to the manipulation
8 of data as numbers, dates, strings, arrays, hashes, and miscellaneous
9 data issues.
10
11 =head1 Data: Numbers
12
13 =head2 Why isn't my octal data interpreted correctly?
14
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".
22
23 This problem shows up most often when people try using chmod(), mkdir(),
24 umask(), or sysopen(), which all want permissions in octal.
25
26     chmod(644,  $file); # WRONG -- perl -w catches this
27     chmod(0644, $file); # right
28
29 =head2 Does perl have a round function?  What about ceil() and floor()?
30 Trig functions?
31
32 For rounding to a certain number of digits, sprintf() or printf() is
33 usually the easiest route.
34
35 The POSIX module (part of the standard perl distribution) implements
36 ceil(), floor(), and a number of other mathematical and trigonometric
37 functions.
38
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.
43
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
48 need yourself.
49
50 =head2 How do I convert bits into ints?
51
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
54 L<perlfunc/"pack">):
55
56     $decimal = pack('B8', '10110110');
57
58 Here's an example of going the other way:
59
60     $binary_string = join('', unpack('B*', "\x29"));
61
62 =head2 How do I multiply matrices?
63
64 Use the Math::Matrix or Math::MatrixReal modules (available from CPAN)
65 or the PDL extension (also available from CPAN).
66
67 =head2 How do I perform an operation on a series of integers?
68
69 To call a function on each element in an array, and collect the
70 results, use:
71
72     @results = map { my_func($_) } @array;
73
74 For example:
75
76     @triple = map { 3 * $_ } @single;
77
78 To call a function on each element of an array, but ignore the
79 results:
80
81     foreach $iterator (@array) {
82         &my_func($iterator);
83     }
84
85 To call a function on each integer in a (small) range, you B<can> use:
86
87     @results = map { &my_func($_) } (5 .. 25);
88
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
91 ranges.  Instead use:
92
93     @results = ();
94     for ($i=5; $i < 500_005; $i++) {
95         push(@results, &my_func($i));
96     }
97
98 =head2 How can I output Roman numerals?
99
100 Get the http://www.perl.com/CPAN/modules/by-module/Roman module.
101
102 =head2 Why aren't my random numbers random?
103
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
108 Phoenix.
109
110 You should also check out the Math::TrulyRandom module from CPAN.
111
112 =head1 Data: Dates
113
114 =head2 How do I find the week-of-the-year/day-of-the-year?
115
116 The day of the year is in the array returned by localtime() (see
117 L<perlfunc/"localtime">):
118
119     $day_of_year = (localtime(time()))[7];
120
121 or more legibly (in 5.004 or higher):
122
123     use Time::localtime;
124     $day_of_year = localtime(time())->yday;
125
126 You can find the week of the year by dividing this by 7:
127
128     $week_of_year = int($day_of_year / 7);
129
130 Of course, this believes that weeks start at zero.
131
132 =head2 How can I compare two date strings?
133
134 Use the Date::Manip or Date::DateCalc modules from CPAN.
135
136 =head2 How can I take a string and turn it into epoch seconds?
137
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.
142
143 =head2 How can I find the Julian Day?
144
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,
148 which should help.
149
150 =head2 Does Perl have a year 2000 problem?
151
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.
159
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.
164
165 =head1 Data: Strings
166
167 =head2 How do I validate input?
168
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.
172
173 =head2 How do I unescape a string?
174
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:
178
179     s/\\(.)/$1/g;
180
181 Note that this won't expand \n or \t or any other special escapes.
182
183 =head2 How do I remove consecutive pairs of characters?
184
185 To turn "abbcccd" into "abccd":
186
187     s/(.)\1/$1/g;
188
189 =head2 How do I expand function calls in a string?
190
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:
194
195     print "My sub returned @{[mysub(1,2,3)]} that time.\n";
196
197 If you prefer scalar context, similar chicanery is also useful for
198 arbitrary expressions:
199
200     print "That yields ${\($n + 5)} widgets\n";
201
202 =head2 How do I find matching/nesting anything?
203
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.
210
211 =head2 How do I reverse a string?
212
213 Use reverse() in a scalar context, as documented in
214 L<perlfunc/reverse>.
215
216     $reversed = reverse $string;
217
218 =head2 How do I expand tabs in a string?
219
220 You can do it the old-fashioned way:
221
222     1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
223
224 Or you can just use the Text::Tabs module (part of the standard perl
225 distribution).
226
227     use Text::Tabs;
228     @expanded_lines = expand(@lines_with_tabs);
229
230 =head2 How do I reformat a paragraph?
231
232 Use Text::Wrap (part of the standard perl distribution):
233
234     use Text::Wrap;
235     print wrap("\t", '  ', @paragraphs);
236
237 =head2 How can I access/change the first N letters of a string?
238
239 There are many ways.  If you just want to grab a copy, use
240 substr:
241
242     $first_byte = substr($a, 0, 1);
243
244 If you want to modify part of a string, the simplest way is often to
245 use substr() as an lvalue:
246
247     substr($a, 0, 3) = "Tom";
248
249 Although those with a regexp kind of thought process will likely prefer
250
251     $a =~ s/^.../Tom/;
252
253 =head2 How do I change the Nth occurrence of something?
254
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.
258
259     $count = 0;
260     s{((whom?)ever)}{
261         ++$count == 5           # is it the 5th?
262             ? "${2}soever"      # yes, swap
263             : $1                # renege and leave it there
264     }igex;
265
266 =head2 How can I count the number of occurrences of a substring within a string?
267
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:
271
272     $string = "ThisXlineXhasXsomeXx'sXinXit":
273     $count = ($string =~ tr/X//);
274     print "There are $count X charcters in the string";
275
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
280 integers:
281
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";
285
286 =head2 How do I capitalize all the words on one line?
287
288 To make the first letter of each word upper case:
289         $line =~ s/\b(\w)/\U$1/g;
290
291 To make the whole line upper case:
292         $line = uc($line);
293
294 To force each word to be lower case, with the first letter upper case:
295         $line =~ s/(\w+)/\u\L$1/g;
296
297 =head2 How can I split a [character] delimited string except when inside
298 [character]? (Comma-separated files)
299
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:
305
306     SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"
307
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):
312
313      @new = ();
314      push(@new, $+) while $text =~ m{
315          "([^\"\\]*(?:\\.[^\"\\]*)*)",?  # groups the phrase inside the quotes
316        | ([^,]+),?
317        | ,
318      }gx;
319      push(@new, undef) if substr($text,-1,1) eq ',';
320
321 Alternatively, the Text::ParseWords module (part of the standard perl
322 distribution) lets you say:
323
324     use Text::ParseWords;
325     @new = quotewords(",", 0, $text);
326
327 =head2 How do I strip blank space from the beginning/end of a string?
328
329 The simplest approach, albeit not the fastest, is probably like this:
330
331     $string =~ s/^\s*(.*?)\s*$/$1/;
332
333 It would be faster to do this in two steps:
334
335     $string =~ s/^\s+//;
336     $string =~ s/\s+$//;
337
338 Or more nicely written as:
339
340     for ($string) {
341         s/^\s+//;
342         s/\s+$//;
343     }
344
345 =head2 How do I extract selected columns from a string?
346
347 Use substr() or unpack(), both documented in L<perlfunc>.
348
349 =head2 How do I find the soundex value of a string?
350
351 Use the standard Text::Soundex module distributed with perl.
352
353 =head2 How can I expand variables in text strings?
354
355 Let's assume that you have a string like:
356
357     $text = 'this has a $foo in it and a $bar';
358     $text =~ s/\$(\w+)/${$1}/g;
359
360 Before version 5 of perl, this had to be done with a double-eval
361 substitution:
362
363     $text =~ s/(\$\w+)/$1/eeg;
364
365 Which is bizarre enough that you'll probably actually need an EEG
366 afterwards. :-)
367
368 =head2 What's wrong with always quoting "$vars"?
369
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.
373
374 If you get used to writing odd things like these:
375
376     print "$var";       # BAD
377     $new = "$old";      # BAD
378     somefunc("$var");   # BAD
379
380 You'll be in trouble.  Those should (in 99.8% of the cases) be
381 the simpler and more direct:
382
383     print $var;
384     $new = $old;
385     somefunc($var);
386
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
389 a reference:
390
391     func(\@array);
392     sub func {
393         my $aref = shift;
394         my $oref = "$aref";  # WRONG
395     }
396
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
400 syscall() function.
401
402 =head2 Why don't my <<HERE documents work?
403
404 Check for these three things:
405
406 =over 4
407
408 =item 1. There must be no space after the << part.
409
410 =item 2. There (probably) should be a semicolon at the end.
411
412 =item 3. You can't (easily) have any space in front of the tag.
413
414 =back
415
416 =head1 Data: Arrays
417
418 =head2 What is the difference between $array[1] and @array[1]?
419
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).
424
425 Sometimes it doesn't make a difference, but sometimes it does.
426 For example, compare:
427
428     $good[0] = `some program that outputs several lines`;
429
430 with
431
432     @bad[0]  = `same program that outputs several lines`;
433
434 The B<-w> flag will warn you about these matters.
435
436 =head2 How can I extract just the unique elements of an array?
437
438 There are several possible ways, depending on whether the array is
439 ordered and whether you wish to preserve the ordering.
440
441 =over 4
442
443 =item a) If @in is sorted, and you want @out to be sorted:
444
445     $prev = 'nonesuch';
446     @out = grep($_ ne $prev && ($prev = $_), @in);
447
448 This is nice in that it doesn't use much extra memory,
449 simulating uniq(1)'s behavior of removing only adjacent
450 duplicates.
451
452 =item b) If you don't know whether @in is sorted:
453
454     undef %saw;
455     @out = grep(!$saw{$_}++, @in);
456
457 =item c) Like (b), but @in contains only small integers:
458
459     @out = grep(!$saw[$_]++, @in);
460
461 =item d) A way to do (b) without any loops or greps:
462
463     undef %saw;
464     @saw{@in} = ();
465     @out = sort keys %saw;  # remove sort if undesired
466
467 =item e) Like (d), but @in contains only small positive integers:
468
469     undef @ary;
470     @ary[@in] = @in;
471     @out = @ary;
472
473 =back
474
475 =head2 How can I tell whether an array contains a certain element?
476
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.
481
482     @blues = qw/azure cerulean teal turquoise lapis-lazuli/;
483     undef %is_blue;
484     for (@blues) { $is_blue{$_} = 1 }
485
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.
488
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:
491
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; }
495
496 Now you check whether $is_tiny_prime[$some_number].
497
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:
500
501     @articles = ( 1..10, 150..2000, 2017 );
502     undef $read;
503     grep (vec($read,$_,1) = 1, @articles);
504
505 Now check whether C<vec($read,$n,1)> is true for some C<$n>.
506
507 Please do not use
508
509     $is_there = grep $_ eq $whatever, @array;
510
511 or worse yet
512
513     $is_there = grep /$whatever/, @array;
514
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?).
518
519 =head2 How do I compute the difference of two arrays?  How do I compute the intersection of two arrays?
520
521 Use a hash.  Here's code to do both and more.  It assumes that
522 each element is unique in a given array:
523
524     @union = @intersection = @difference = ();
525     %count = ();
526     foreach $element (@array1, @array2) { $count{$element}++ }
527     foreach $element (keys %count) {
528         push @union, $element;
529         push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
530     }
531
532 =head2 How do I find the first array element for which a condition is true?
533
534 You can use this if you care about the index:
535
536     for ($i=0; $i < @array; $i++) {
537         if ($array[$i] eq "Waldo") {
538             $found_index = $i;
539             last;
540         }
541     }
542
543 Now C<$found_index> has what you want.
544
545 =head2 How do I handle linked lists?
546
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
550 at arbitrary points.
551
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
554 to do.
555
556 =head2 How do I handle circular lists?
557
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:
560
561     unshift(@array, pop(@array));  # the last shall be first
562     push(@array, shift(@array));   # and vice versa
563
564 =head2 How do I shuffle an array randomly?
565
566 Here's a shuffling algorithm which works its way through the list,
567 randomly picking another element to swap the current element with:
568
569     srand;
570     @new = ();
571     @old = 1 .. 10;  # just a demo
572     while (@old) {
573         push(@new, splice(@old, rand @old, 1));
574     }
575
576 For large arrays, this avoids a lot of the reshuffling:
577
578     srand;
579     @new = ();
580     @old = 1 .. 10000;  # just a demo
581     for( @old ){
582         my $r = rand @new+1;
583         push(@new,$new[$r]);
584         $new[$r] = $_;
585     }
586
587 =head2 How do I process/modify each element of an array?
588
589 Use C<for>/C<foreach>:
590
591     for (@lines) {
592         s/foo/bar/;
593         tr[a-z][A-Z];
594     }
595
596 Here's another; let's compute spherical volumes:
597
598     for (@radii) {
599         $_ **= 3;
600         $_ *= (4/3) * 3.14159;  # this will be constant folded
601     }
602
603 =head2 How do I select a random element from an array?
604
605 Use the rand() function (see L<perlfunc/rand>):
606
607     srand;                      # not needed for 5.004 and later
608     $index   = rand @array;
609     $element = $array[$index];
610
611 =head2 How do I permute N elements of a list?
612
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:
616
617     #!/usr/bin/perl -n
618     # permute - tchrist@perl.com
619     permut([split], []);
620     sub permut {
621         my @head = @{ $_[0] };
622         my @tail = @{ $_[1] };
623         unless (@head) {
624             # stop recursing when there are no elements in the head
625             print "@tail\n";
626         } else {
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) {
631                 @newhead = @head;
632                 @newtail = @tail;
633                 unshift(@newtail, splice(@newhead, $i, 1));
634                 permut([@newhead], [@newtail]);
635             }
636         }
637     }
638
639 =head2 How do I sort an array by (anything)?
640
641 Supply a comparison function to sort() (described in L<perlfunc/sort>):
642
643     @list = sort { $a <=> $b } @list;
644
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.
648
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
654 case-insensitively.
655
656     @idx = ();
657     for (@data) {
658         ($item) = /\d+\s*(\S+)/;
659         push @idx, uc($item);
660     }
661     @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];
662
663 Which could also be written this way, using a trick
664 that's come to be known as the Schwartzian Transform:
665
666     @sorted = map  { $_->[0] }
667               sort { $a->[1] cmp $b->[1] }
668               map  { [ $_, uc((/\d+\s*(\S+) )[0] ] } @data;
669
670 If you need to sort on several fields, the following paradigm is useful.
671
672     @sorted = sort { field1($a) <=> field1($b) ||
673                      field2($a) cmp field2($b) ||
674                      field3($a) cmp field3($b)
675                    }     @data;
676
677 This can be conveniently combined with precalculation of keys as given
678 above.
679
680 See http://www.perl.com/CPAN/doc/FMTEYEWTK/sort.html for more about
681 this approach.
682
683 See also the question below on sorting hashes.
684
685 =head2 How do I manipulate arrays of bits?
686
687 Use pack() and unpack(), or else vec() and the bitwise operations.
688
689 For example, this sets $vec to have bit N set if $ints[N] was set:
690
691     $vec = '';
692     foreach(@ints) { vec($vec,$_,1) = 1 }
693
694 And here's how, given a vector in $vec, you can
695 get those bits into your @ints array:
696
697     sub bitvec_to_list {
698         my $vec = shift;
699         my @ints;
700         # Find null-byte density then select best algorithm
701         if ($vec =~ tr/\0// / length $vec > 0.95) {
702             use integer;
703             my $i;
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);
715             }
716         } else {
717             # This method is a fast general algorithm
718             use integer;
719             my $bits = unpack "b*", $vec;
720             push @ints, 0 if $bits =~ s/^(\d)// && $1;
721             push @ints, pos $bits while($bits =~ /1/g);
722         }
723         return \@ints;
724     }
725
726 This method gets faster the more sparse the bit vector is.
727 (Courtesy of Tim Bunce and Winfried Koenig.)
728
729 =head2 Why does defined() return true on empty arrays and hashes?
730
731 See L<perlfunc/defined> in the 5.004 release or later of Perl.
732
733 =head1 Data: Hashes (Associative Arrays)
734
735 =head2 How do I process an entire hash?
736
737 Use the each() function (see L<perlfunc/each>) if you don't care
738 whether it's sorted:
739
740     while (($key,$value) = each %hash) {
741         print "$key = $value\n";
742     }
743
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.
746
747 =head2 What happens if I add or remove keys from a hash while iterating over it?
748
749 Don't do that.
750
751 =head2 How do I look up a hash element by value?
752
753 Create a reverse hash:
754
755     %by_value = reverse %by_key;
756     $key = $by_value{$value};
757
758 That's not particularly efficient.  It would be more space-efficient
759 to use:
760
761     while (($key, $value) = each %by_key) {
762         $by_value{$value} = $key;
763     }
764
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.
767
768 =head2 How can I know how many entries are in a hash?
769
770 If you mean how many keys, then all you have to do is
771 take the scalar sense of the keys() function:
772
773         $num_keys = scalar keys %hash;
774
775 In void context it just resets the iterator, which is faster
776 for tied hashes.
777
778 =head2 How do I sort a hash (optionally by value instead of key)?
779
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
782 keys or values:
783
784     @keys = sort keys %hash;    # sorted by key
785     @keys = sort {
786                     $hash{$a} cmp $hash{$b}
787             } keys %hash;       # and by value
788
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
792 L<perllocale>).
793
794     @keys = sort {
795                 $hash{$b} <=> $hash{$a}
796                           ||
797                 length($b) <=> length($a)
798                           ||
799                       $a cmp $b
800     } keys %hash;
801
802 =head2 How can I always keep my hash sorted?
803
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">.
806
807 =head2 What's the difference between "delete" and "undef" with hashes?
808
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.
816
817 Pictures help...  here's the C<%ary> table:
818
819           keys  values
820         +------+------+
821         |  a   |  3   |
822         |  x   |  7   |
823         |  d   |  0   |
824         |  e   |  2   |
825         +------+------+
826
827 And these conditions hold
828
829         $ary{'a'}                       is true
830         $ary{'d'}                       is false
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
835
836 If you now say
837
838         undef $ary{'a'}
839
840 your table now reads:
841
842
843           keys  values
844         +------+------+
845         |  a   | undef|
846         |  x   |  7   |
847         |  d   |  0   |
848         |  e   |  2   |
849         +------+------+
850
851 and these conditions now hold; changes in caps:
852
853         $ary{'a'}                       is FALSE
854         $ary{'d'}                       is false
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
859
860 Notice the last two: you have an undef value, but a defined key!
861
862 Now, consider this:
863
864         delete $ary{'a'}
865
866 your table now reads:
867
868           keys  values
869         +------+------+
870         |  x   |  7   |
871         |  d   |  0   |
872         |  e   |  2   |
873         +------+------+
874
875 and these conditions now hold; changes in caps:
876
877         $ary{'a'}                       is false
878         $ary{'d'}                       is false
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
883
884 See, the whole entry is gone!
885
886 =head2 Why don't my tied hashes make the defined/exists distinction?
887
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.
894
895 =head2 How do I reset an each() operation part-way through?
896
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.
901
902 =head2 How can I get the unique keys from two hashes?
903
904 First you extract the keys from the hashes into arrays, and then solve
905 the uniquifying the array problem described above.  For example:
906
907     %seen = ();
908     for $element (keys(%foo), keys(%bar)) {
909         $seen{$element}++;
910     }
911     @uniq = keys %seen;
912
913 Or more succinctly:
914
915     @uniq = keys %{{%foo,%bar}};
916
917 Or if you really want to save space:
918
919     %seen = ();
920     while (defined ($key = each %foo)) {
921         $seen{$key}++;
922     }
923     while (defined ($key = each %bar)) {
924         $seen{$key}++;
925     }
926     @uniq = keys %seen;
927
928 =head2 How can I store a multidimensional array in a DBM file?
929
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.
933
934 =head2 How can I make my hash remember the order I put elements into it?
935
936 Use the Tie::IxHash from CPAN.
937
938 =head2 Why does passing a subroutine an undefined element in a hash create it?
939
940 If you say something like:
941
942     somefunc($hash{"nonesuch key here"});
943
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.
948
949 This has been fixed as of perl5.004.
950
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
953 awk's behavior.
954
955 =head2 How can I make the Perl equivalent of a C structure/C++ class/hash 
956 or array of hashes or arrays?
957
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>.
961
962 =head2 How can I use a reference as a hash key?
963
964 You can't do this directly, but you could use the standard Tie::Refhash
965 module distributed with perl.
966
967 =head1 Data: Misc
968
969 =head2 How do I handle binary data correctly?
970
971 Perl is binary clean, so this shouldn't be a problem.  For example,
972 this works fine (assuming the files are found):
973
974     if (`cat /vmunix` =~ /gzip/) {
975         print "Your kernel is GNU-zip enabled!\n";
976     }
977
978 On some systems, however, you have to play tedious games with "text"
979 versus "binary" files.  See L<perlfunc/"binmode">.
980
981 If you're concerned about 8-bit ASCII data, then see L<perllocale>.
982
983 If you want to deal with multi-byte characters, however, there are
984 some gotchas.  See the section on Regular Expressions.
985
986 =head2 How do I determine whether a scalar is a number/whole/integer/float?
987
988 Assuming that you don't care about IEEE notations like "NaN" or
989 "Infinity", you probably just want to use a regular expression.
990
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+)$/;
997    warn "not a C float"
998        unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
999
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.
1005
1006 =head2 How do I keep persistent data across program calls?
1007
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.
1011
1012 =head2 How do I print out or copy a recursive data structure?
1013
1014 The Data::Dumper module on CPAN is nice for printing out
1015 data structures, and FreezeThaw for copying them.  For example:
1016
1017     use FreezeThaw qw(freeze thaw);
1018     $new = thaw freeze $old;
1019
1020 Where $old can be (a reference to) any kind of data structure you'd like.
1021 It will be deeply copied.
1022
1023 =head2 How do I define methods for every class/object?
1024
1025 Use the UNIVERSAL class (see L<UNIVERSAL>).
1026
1027 =head2 How do I verify a credit card checksum?
1028
1029 Get the Business::CreditCard module from CPAN.
1030
1031 =head1 AUTHOR AND COPYRIGHT
1032
1033 Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
1034 All rights reserved.  See L<perlfaq> for distribution information.