[inseparable changes from match from perl-5.003_97g to perl-5.003_97h]
[p5sagit/p5-mst-13.2.git] / pod / perlfaq4.pod
CommitLineData
68dc0745 1=head1 NAME
2
46fc3d4c 3perlfaq4 - Data Manipulation ($Revision: 1.18 $, $Date: 1997/04/23 18:04:37 $)
68dc0745 4
5=head1 DESCRIPTION
6
7The section of the FAQ answers question related to the manipulation
8of data as numbers, dates, strings, arrays, hashes, and miscellaneous
9data issues.
10
11=head1 Data: Numbers
12
46fc3d4c 13=head2 Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?
14
15Internally, your computer represents floating-point numbers in binary.
16Floating-point numbers read in from a file, or appearing as literals
17in your program, are converted from their decimal floating-point
18representation (eg, 19.95) to the internal binary representation.
19
20However, 19.95 can't be precisely represented as a binary
21floating-point number, just like 1/3 can't be exactly represented as a
22decimal floating-point number. The computer's binary representation
23of 19.95, therefore, isn't exactly 19.95.
24
25When a floating-point number gets printed, the binary floating-point
26representation is converted back to decimal. These decimal numbers
27are displayed in either the format you specify with printf(), or the
28current output format for numbers (see L<perlvar/"$#"> if you use
29print. C<$#> has a different default value in Perl5 than it did in
30Perl4. Changing C<$#> yourself is deprecated.
31
32This affects B<all> computer languages that represent decimal
33floating-point numbers in binary, not just Perl. Perl provides
34arbitrary-precision decimal numbers with the Math::BigFloat module
35(part of the standard Perl distribution), but mathematical operations
36are consequently slower.
37
38To get rid of the superfluous digits, just use a format (eg,
39C<printf("%.2f", 19.95)>) to get the required precision.
40
68dc0745 41=head2 Why isn't my octal data interpreted correctly?
42
43Perl only understands octal and hex numbers as such when they occur
44as literals in your program. If they are read in from somewhere and
45assigned, no automatic conversion takes place. You must explicitly
46use oct() or hex() if you want the values converted. oct() interprets
47both hex ("0x350") numbers and octal ones ("0350" or even without the
48leading "0", like "377"), while hex() only converts hexadecimal ones,
49with or without a leading "0x", like "0x255", "3A", "ff", or "deadbeef".
50
51This problem shows up most often when people try using chmod(), mkdir(),
52umask(), or sysopen(), which all want permissions in octal.
53
54 chmod(644, $file); # WRONG -- perl -w catches this
55 chmod(0644, $file); # right
56
57=head2 Does perl have a round function? What about ceil() and floor()?
58Trig functions?
59
60For rounding to a certain number of digits, sprintf() or printf() is
61usually the easiest route.
62
63The POSIX module (part of the standard perl distribution) implements
64ceil(), floor(), and a number of other mathematical and trigonometric
65functions.
66
46fc3d4c 67In 5.000 to 5.003 Perls, trigonometry was done in the Math::Complex
68module. With 5.004, the Math::Trig module (part of the standard perl
69distribution) implements the trigonometric functions. Internally it
70uses the Math::Complex module and some functions can break out from
71the real axis into the complex plane, for example the inverse sine of
722.
68dc0745 73
74Rounding in financial applications can have serious implications, and
75the rounding method used should be specified precisely. In these
76cases, it probably pays not to trust whichever system rounding is
77being used by Perl, but to instead implement the rounding function you
78need yourself.
79
80=head2 How do I convert bits into ints?
81
82To turn a string of 1s and 0s like '10110110' into a scalar containing
83its binary value, use the pack() function (documented in
84L<perlfunc/"pack">):
85
86 $decimal = pack('B8', '10110110');
87
88Here's an example of going the other way:
89
90 $binary_string = join('', unpack('B*', "\x29"));
91
92=head2 How do I multiply matrices?
93
94Use the Math::Matrix or Math::MatrixReal modules (available from CPAN)
95or the PDL extension (also available from CPAN).
96
97=head2 How do I perform an operation on a series of integers?
98
99To call a function on each element in an array, and collect the
100results, use:
101
102 @results = map { my_func($_) } @array;
103
104For example:
105
106 @triple = map { 3 * $_ } @single;
107
108To call a function on each element of an array, but ignore the
109results:
110
111 foreach $iterator (@array) {
112 &my_func($iterator);
113 }
114
115To call a function on each integer in a (small) range, you B<can> use:
116
117 @results = map { &my_func($_) } (5 .. 25);
118
119but you should be aware that the C<..> operator creates an array of
120all integers in the range. This can take a lot of memory for large
121ranges. Instead use:
122
123 @results = ();
124 for ($i=5; $i < 500_005; $i++) {
125 push(@results, &my_func($i));
126 }
127
128=head2 How can I output Roman numerals?
129
130Get the http://www.perl.com/CPAN/modules/by-module/Roman module.
131
132=head2 Why aren't my random numbers random?
133
134The short explanation is that you're getting pseudorandom numbers, not
135random ones, because that's how these things work. A longer
136explanation is available on
137http://www.perl.com/CPAN/doc/FMTEYEWTK/random, courtesy of Tom
138Phoenix.
139
140You should also check out the Math::TrulyRandom module from CPAN.
141
142=head1 Data: Dates
143
144=head2 How do I find the week-of-the-year/day-of-the-year?
145
146The day of the year is in the array returned by localtime() (see
147L<perlfunc/"localtime">):
148
149 $day_of_year = (localtime(time()))[7];
150
151or more legibly (in 5.004 or higher):
152
153 use Time::localtime;
154 $day_of_year = localtime(time())->yday;
155
156You can find the week of the year by dividing this by 7:
157
158 $week_of_year = int($day_of_year / 7);
159
160Of course, this believes that weeks start at zero.
161
162=head2 How can I compare two date strings?
163
164Use the Date::Manip or Date::DateCalc modules from CPAN.
165
166=head2 How can I take a string and turn it into epoch seconds?
167
168If it's a regular enough string that it always has the same format,
169you can split it up and pass the parts to timelocal in the standard
170Time::Local module. Otherwise, you should look into one of the
171Date modules from CPAN.
172
173=head2 How can I find the Julian Day?
174
175Neither Date::Manip nor Date::DateCalc deal with Julian days.
176Instead, there is an example of Julian date calculation in
177http://www.perl.com/CPAN/authors/David_Muir_Sharnoff/modules/Time/JulianDay.pm.gz,
178which should help.
179
180=head2 Does Perl have a year 2000 problem?
181
182Not unless you use Perl to create one. The date and time functions
183supplied with perl (gmtime and localtime) supply adequate information
184to determine the year well beyond 2000 (2038 is when trouble strikes).
185The year returned by these functions when used in an array context is
186the year minus 1900. For years between 1910 and 1999 this I<happens>
187to be a 2-digit decimal number. To avoid the year 2000 problem simply
188do not treat the year as a 2-digit number. It isn't.
189
190When gmtime() and localtime() are used in a scalar context they return
191a timestamp string that contains a fully-expanded year. For example,
192C<$timestamp = gmtime(1005613200)> sets $timestamp to "Tue Nov 13 01:00:00
1932001". There's no year 2000 problem here.
194
195=head1 Data: Strings
196
197=head2 How do I validate input?
198
199The answer to this question is usually a regular expression, perhaps
200with auxiliary logic. See the more specific questions (numbers, email
201addresses, etc.) for details.
202
203=head2 How do I unescape a string?
204
205It depends just what you mean by "escape". URL escapes are dealt with
206in L<perlfaq9>. Shell escapes with the backslash (\)
207character are removed with:
208
209 s/\\(.)/$1/g;
210
211Note that this won't expand \n or \t or any other special escapes.
212
213=head2 How do I remove consecutive pairs of characters?
214
215To turn "abbcccd" into "abccd":
216
217 s/(.)\1/$1/g;
218
219=head2 How do I expand function calls in a string?
220
221This is documented in L<perlref>. In general, this is fraught with
222quoting and readability problems, but it is possible. To interpolate
223a subroutine call (in a list context) into a string:
224
225 print "My sub returned @{[mysub(1,2,3)]} that time.\n";
226
227If you prefer scalar context, similar chicanery is also useful for
228arbitrary expressions:
229
230 print "That yields ${\($n + 5)} widgets\n";
231
46fc3d4c 232See also "How can I expand variables in text strings?" in this section
233of the FAQ.
234
68dc0745 235=head2 How do I find matching/nesting anything?
236
237This isn't something that can be tackled in one regular expression, no
238matter how complicated. To find something between two single characters,
239a pattern like C</x([^x]*)x/> will get the intervening bits in $1. For
240multiple ones, then something more like C</alpha(.*?)omega/> would
241be needed. But none of these deals with nested patterns, nor can they.
242For that you'll have to write a parser.
243
244=head2 How do I reverse a string?
245
246Use reverse() in a scalar context, as documented in
247L<perlfunc/reverse>.
248
249 $reversed = reverse $string;
250
251=head2 How do I expand tabs in a string?
252
253You can do it the old-fashioned way:
254
255 1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
256
257Or you can just use the Text::Tabs module (part of the standard perl
258distribution).
259
260 use Text::Tabs;
261 @expanded_lines = expand(@lines_with_tabs);
262
263=head2 How do I reformat a paragraph?
264
265Use Text::Wrap (part of the standard perl distribution):
266
267 use Text::Wrap;
268 print wrap("\t", ' ', @paragraphs);
269
46fc3d4c 270The paragraphs you give to Text::Wrap may not contain embedded
271newlines. Text::Wrap doesn't justify the lines (flush-right).
272
68dc0745 273=head2 How can I access/change the first N letters of a string?
274
275There are many ways. If you just want to grab a copy, use
276substr:
277
278 $first_byte = substr($a, 0, 1);
279
280If you want to modify part of a string, the simplest way is often to
281use substr() as an lvalue:
282
283 substr($a, 0, 3) = "Tom";
284
285Although those with a regexp kind of thought process will likely prefer
286
287 $a =~ s/^.../Tom/;
288
289=head2 How do I change the Nth occurrence of something?
290
291You have to keep track. For example, let's say you want
292to change the fifth occurrence of "whoever" or "whomever"
3fe9a6f1 293into "whosoever" or "whomsoever", case insensitively.
68dc0745 294
295 $count = 0;
296 s{((whom?)ever)}{
297 ++$count == 5 # is it the 5th?
298 ? "${2}soever" # yes, swap
299 : $1 # renege and leave it there
300 }igex;
301
302=head2 How can I count the number of occurrences of a substring within a string?
303
304There are a number of ways, with varying efficiency: If you want a
305count of a certain single character (X) within a string, you can use the
306C<tr///> function like so:
307
308 $string = "ThisXlineXhasXsomeXx'sXinXit":
309 $count = ($string =~ tr/X//);
46fc3d4c 310 print "There are $count X charcters in the string";
68dc0745 311
312This is fine if you are just looking for a single character. However,
313if you are trying to count multiple character substrings within a
314larger string, C<tr///> won't work. What you can do is wrap a while()
315loop around a global pattern match. For example, let's count negative
316integers:
317
318 $string = "-9 55 48 -2 23 -76 4 14 -44";
319 while ($string =~ /-\d+/g) { $count++ }
320 print "There are $count negative numbers in the string";
321
322=head2 How do I capitalize all the words on one line?
323
324To make the first letter of each word upper case:
3fe9a6f1 325
68dc0745 326 $line =~ s/\b(\w)/\U$1/g;
327
46fc3d4c 328This has the strange effect of turning "C<don't do it>" into "C<Don'T
329Do It>". Sometimes you might want this, instead (Suggested by Brian
330Foy E<lt>comdog@computerdog.comE<gt>):
331
332 $string =~ s/ (
333 (^\w) #at the beginning of the line
334 | # or
335 (\s\w) #preceded by whitespace
336 )
337 /\U$1/xg;
338 $string =~ /([\w']+)/\u\L$1/g;
339
68dc0745 340To make the whole line upper case:
3fe9a6f1 341
68dc0745 342 $line = uc($line);
343
344To force each word to be lower case, with the first letter upper case:
3fe9a6f1 345
68dc0745 346 $line =~ s/(\w+)/\u\L$1/g;
347
348=head2 How can I split a [character] delimited string except when inside
349[character]? (Comma-separated files)
350
351Take the example case of trying to split a string that is comma-separated
352into its different fields. (We'll pretend you said comma-separated, not
353comma-delimited, which is different and almost never what you mean.) You
354can't use C<split(/,/)> because you shouldn't split if the comma is inside
355quotes. For example, take a data line like this:
356
357 SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"
358
359Due to the restriction of the quotes, this is a fairly complex
360problem. Thankfully, we have Jeffrey Friedl, author of a highly
361recommended book on regular expressions, to handle these for us. He
362suggests (assuming your string is contained in $text):
363
364 @new = ();
365 push(@new, $+) while $text =~ m{
366 "([^\"\\]*(?:\\.[^\"\\]*)*)",? # groups the phrase inside the quotes
367 | ([^,]+),?
368 | ,
369 }gx;
370 push(@new, undef) if substr($text,-1,1) eq ',';
371
46fc3d4c 372If you want to represent quotation marks inside a
373quotation-mark-delimited field, escape them with backslashes (eg,
374C<"like \"this\""). Unescaping them is a task addressed earlier in
375this section.
376
68dc0745 377Alternatively, the Text::ParseWords module (part of the standard perl
378distribution) lets you say:
379
380 use Text::ParseWords;
381 @new = quotewords(",", 0, $text);
382
383=head2 How do I strip blank space from the beginning/end of a string?
384
385The simplest approach, albeit not the fastest, is probably like this:
386
387 $string =~ s/^\s*(.*?)\s*$/$1/;
388
389It would be faster to do this in two steps:
390
391 $string =~ s/^\s+//;
392 $string =~ s/\s+$//;
393
394Or more nicely written as:
395
396 for ($string) {
397 s/^\s+//;
398 s/\s+$//;
399 }
400
401=head2 How do I extract selected columns from a string?
402
403Use substr() or unpack(), both documented in L<perlfunc>.
404
405=head2 How do I find the soundex value of a string?
406
407Use the standard Text::Soundex module distributed with perl.
408
409=head2 How can I expand variables in text strings?
410
411Let's assume that you have a string like:
412
413 $text = 'this has a $foo in it and a $bar';
414 $text =~ s/\$(\w+)/${$1}/g;
415
416Before version 5 of perl, this had to be done with a double-eval
417substitution:
418
419 $text =~ s/(\$\w+)/$1/eeg;
420
421Which is bizarre enough that you'll probably actually need an EEG
422afterwards. :-)
423
46fc3d4c 424See also "How do I expand function calls in a string?" in this section
425of the FAQ.
426
68dc0745 427=head2 What's wrong with always quoting "$vars"?
428
429The problem is that those double-quotes force stringification,
430coercing numbers and references into strings, even when you
431don't want them to be.
432
433If you get used to writing odd things like these:
434
435 print "$var"; # BAD
436 $new = "$old"; # BAD
437 somefunc("$var"); # BAD
438
439You'll be in trouble. Those should (in 99.8% of the cases) be
440the simpler and more direct:
441
442 print $var;
443 $new = $old;
444 somefunc($var);
445
446Otherwise, besides slowing you down, you're going to break code when
447the thing in the scalar is actually neither a string nor a number, but
448a reference:
449
450 func(\@array);
451 sub func {
452 my $aref = shift;
453 my $oref = "$aref"; # WRONG
454 }
455
456You can also get into subtle problems on those few operations in Perl
457that actually do care about the difference between a string and a
458number, such as the magical C<++> autoincrement operator or the
459syscall() function.
460
461=head2 Why don't my <<HERE documents work?
462
463Check for these three things:
464
465=over 4
466
467=item 1. There must be no space after the << part.
468
469=item 2. There (probably) should be a semicolon at the end.
470
471=item 3. You can't (easily) have any space in front of the tag.
472
473=back
474
475=head1 Data: Arrays
476
477=head2 What is the difference between $array[1] and @array[1]?
478
479The former is a scalar value, the latter an array slice, which makes
480it a list with one (scalar) value. You should use $ when you want a
481scalar value (most of the time) and @ when you want a list with one
482scalar value in it (very, very rarely; nearly never, in fact).
483
484Sometimes it doesn't make a difference, but sometimes it does.
485For example, compare:
486
487 $good[0] = `some program that outputs several lines`;
488
489with
490
491 @bad[0] = `same program that outputs several lines`;
492
493The B<-w> flag will warn you about these matters.
494
495=head2 How can I extract just the unique elements of an array?
496
497There are several possible ways, depending on whether the array is
498ordered and whether you wish to preserve the ordering.
499
500=over 4
501
502=item a) If @in is sorted, and you want @out to be sorted:
503
504 $prev = 'nonesuch';
505 @out = grep($_ ne $prev && ($prev = $_), @in);
506
507This is nice in that it doesn't use much extra memory,
508simulating uniq(1)'s behavior of removing only adjacent
509duplicates.
510
511=item b) If you don't know whether @in is sorted:
512
513 undef %saw;
514 @out = grep(!$saw{$_}++, @in);
515
516=item c) Like (b), but @in contains only small integers:
517
518 @out = grep(!$saw[$_]++, @in);
519
520=item d) A way to do (b) without any loops or greps:
521
522 undef %saw;
523 @saw{@in} = ();
524 @out = sort keys %saw; # remove sort if undesired
525
526=item e) Like (d), but @in contains only small positive integers:
527
528 undef @ary;
529 @ary[@in] = @in;
530 @out = @ary;
531
532=back
533
534=head2 How can I tell whether an array contains a certain element?
535
536There are several ways to approach this. If you are going to make
537this query many times and the values are arbitrary strings, the
538fastest way is probably to invert the original array and keep an
539associative array lying about whose keys are the first array's values.
540
541 @blues = qw/azure cerulean teal turquoise lapis-lazuli/;
542 undef %is_blue;
543 for (@blues) { $is_blue{$_} = 1 }
544
545Now you can check whether $is_blue{$some_color}. It might have been a
546good idea to keep the blues all in a hash in the first place.
547
548If the values are all small integers, you could use a simple indexed
549array. This kind of an array will take up less space:
550
551 @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
552 undef @is_tiny_prime;
553 for (@primes) { $is_tiny_prime[$_] = 1; }
554
555Now you check whether $is_tiny_prime[$some_number].
556
557If the values in question are integers instead of strings, you can save
558quite a lot of space by using bit strings instead:
559
560 @articles = ( 1..10, 150..2000, 2017 );
561 undef $read;
562 grep (vec($read,$_,1) = 1, @articles);
563
564Now check whether C<vec($read,$n,1)> is true for some C<$n>.
565
566Please do not use
567
568 $is_there = grep $_ eq $whatever, @array;
569
570or worse yet
571
572 $is_there = grep /$whatever/, @array;
573
574These are slow (checks every element even if the first matches),
575inefficient (same reason), and potentially buggy (what if there are
576regexp characters in $whatever?).
577
578=head2 How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
579
580Use a hash. Here's code to do both and more. It assumes that
581each element is unique in a given array:
582
583 @union = @intersection = @difference = ();
584 %count = ();
585 foreach $element (@array1, @array2) { $count{$element}++ }
586 foreach $element (keys %count) {
587 push @union, $element;
588 push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
589 }
590
591=head2 How do I find the first array element for which a condition is true?
592
593You can use this if you care about the index:
594
595 for ($i=0; $i < @array; $i++) {
596 if ($array[$i] eq "Waldo") {
597 $found_index = $i;
598 last;
599 }
600 }
601
602Now C<$found_index> has what you want.
603
604=head2 How do I handle linked lists?
605
606In general, you usually don't need a linked list in Perl, since with
607regular arrays, you can push and pop or shift and unshift at either end,
608or you can use splice to add and/or remove arbitrary number of elements
609at arbitrary points.
610
611If you really, really wanted, you could use structures as described in
612L<perldsc> or L<perltoot> and do just what the algorithm book tells you
613to do.
614
615=head2 How do I handle circular lists?
616
617Circular lists could be handled in the traditional fashion with linked
618lists, or you could just do something like this with an array:
619
620 unshift(@array, pop(@array)); # the last shall be first
621 push(@array, shift(@array)); # and vice versa
622
623=head2 How do I shuffle an array randomly?
624
625Here's a shuffling algorithm which works its way through the list,
626randomly picking another element to swap the current element with:
627
628 srand;
629 @new = ();
630 @old = 1 .. 10; # just a demo
631 while (@old) {
632 push(@new, splice(@old, rand @old, 1));
633 }
634
635For large arrays, this avoids a lot of the reshuffling:
636
637 srand;
638 @new = ();
639 @old = 1 .. 10000; # just a demo
640 for( @old ){
641 my $r = rand @new+1;
642 push(@new,$new[$r]);
643 $new[$r] = $_;
644 }
645
646=head2 How do I process/modify each element of an array?
647
648Use C<for>/C<foreach>:
649
650 for (@lines) {
651 s/foo/bar/;
652 tr[a-z][A-Z];
653 }
654
655Here's another; let's compute spherical volumes:
656
657 for (@radii) {
658 $_ **= 3;
659 $_ *= (4/3) * 3.14159; # this will be constant folded
660 }
661
662=head2 How do I select a random element from an array?
663
664Use the rand() function (see L<perlfunc/rand>):
665
666 srand; # not needed for 5.004 and later
667 $index = rand @array;
668 $element = $array[$index];
669
670=head2 How do I permute N elements of a list?
671
672Here's a little program that generates all permutations
673of all the words on each line of input. The algorithm embodied
674in the permut() function should work on any list:
675
676 #!/usr/bin/perl -n
677 # permute - tchrist@perl.com
678 permut([split], []);
679 sub permut {
680 my @head = @{ $_[0] };
681 my @tail = @{ $_[1] };
682 unless (@head) {
683 # stop recursing when there are no elements in the head
684 print "@tail\n";
685 } else {
686 # for all elements in @head, move one from @head to @tail
687 # and call permut() on the new @head and @tail
688 my(@newhead,@newtail,$i);
689 foreach $i (0 .. $#head) {
690 @newhead = @head;
691 @newtail = @tail;
692 unshift(@newtail, splice(@newhead, $i, 1));
693 permut([@newhead], [@newtail]);
694 }
695 }
696 }
697
698=head2 How do I sort an array by (anything)?
699
700Supply a comparison function to sort() (described in L<perlfunc/sort>):
701
702 @list = sort { $a <=> $b } @list;
703
704The default sort function is cmp, string comparison, which would
705sort C<(1, 2, 10)> into C<(1, 10, 2)>. C<E<lt>=E<gt>>, used above, is
706the numerical comparison operator.
707
708If you have a complicated function needed to pull out the part you
709want to sort on, then don't do it inside the sort function. Pull it
710out first, because the sort BLOCK can be called many times for the
711same element. Here's an example of how to pull out the first word
712after the first number on each item, and then sort those words
713case-insensitively.
714
715 @idx = ();
716 for (@data) {
717 ($item) = /\d+\s*(\S+)/;
718 push @idx, uc($item);
719 }
720 @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];
721
722Which could also be written this way, using a trick
723that's come to be known as the Schwartzian Transform:
724
725 @sorted = map { $_->[0] }
726 sort { $a->[1] cmp $b->[1] }
46fc3d4c 727 map { [ $_, uc((/\d+\s*(\S+)/ )[0] ] } @data;
68dc0745 728
729If you need to sort on several fields, the following paradigm is useful.
730
731 @sorted = sort { field1($a) <=> field1($b) ||
732 field2($a) cmp field2($b) ||
733 field3($a) cmp field3($b)
734 } @data;
735
736This can be conveniently combined with precalculation of keys as given
737above.
738
739See http://www.perl.com/CPAN/doc/FMTEYEWTK/sort.html for more about
740this approach.
741
742See also the question below on sorting hashes.
743
744=head2 How do I manipulate arrays of bits?
745
746Use pack() and unpack(), or else vec() and the bitwise operations.
747
748For example, this sets $vec to have bit N set if $ints[N] was set:
749
750 $vec = '';
751 foreach(@ints) { vec($vec,$_,1) = 1 }
752
753And here's how, given a vector in $vec, you can
754get those bits into your @ints array:
755
756 sub bitvec_to_list {
757 my $vec = shift;
758 my @ints;
759 # Find null-byte density then select best algorithm
760 if ($vec =~ tr/\0// / length $vec > 0.95) {
761 use integer;
762 my $i;
763 # This method is faster with mostly null-bytes
764 while($vec =~ /[^\0]/g ) {
765 $i = -9 + 8 * pos $vec;
766 push @ints, $i if vec($vec, ++$i, 1);
767 push @ints, $i if vec($vec, ++$i, 1);
768 push @ints, $i if vec($vec, ++$i, 1);
769 push @ints, $i if vec($vec, ++$i, 1);
770 push @ints, $i if vec($vec, ++$i, 1);
771 push @ints, $i if vec($vec, ++$i, 1);
772 push @ints, $i if vec($vec, ++$i, 1);
773 push @ints, $i if vec($vec, ++$i, 1);
774 }
775 } else {
776 # This method is a fast general algorithm
777 use integer;
778 my $bits = unpack "b*", $vec;
779 push @ints, 0 if $bits =~ s/^(\d)// && $1;
780 push @ints, pos $bits while($bits =~ /1/g);
781 }
782 return \@ints;
783 }
784
785This method gets faster the more sparse the bit vector is.
786(Courtesy of Tim Bunce and Winfried Koenig.)
787
788=head2 Why does defined() return true on empty arrays and hashes?
789
790See L<perlfunc/defined> in the 5.004 release or later of Perl.
791
792=head1 Data: Hashes (Associative Arrays)
793
794=head2 How do I process an entire hash?
795
796Use the each() function (see L<perlfunc/each>) if you don't care
797whether it's sorted:
798
799 while (($key,$value) = each %hash) {
800 print "$key = $value\n";
801 }
802
803If you want it sorted, you'll have to use foreach() on the result of
804sorting the keys as shown in an earlier question.
805
806=head2 What happens if I add or remove keys from a hash while iterating over it?
807
808Don't do that.
809
810=head2 How do I look up a hash element by value?
811
812Create a reverse hash:
813
814 %by_value = reverse %by_key;
815 $key = $by_value{$value};
816
817That's not particularly efficient. It would be more space-efficient
818to use:
819
820 while (($key, $value) = each %by_key) {
821 $by_value{$value} = $key;
822 }
823
824If your hash could have repeated values, the methods above will only
825find one of the associated keys. This may or may not worry you.
826
827=head2 How can I know how many entries are in a hash?
828
829If you mean how many keys, then all you have to do is
830take the scalar sense of the keys() function:
831
3fe9a6f1 832 $num_keys = scalar keys %hash;
68dc0745 833
834In void context it just resets the iterator, which is faster
835for tied hashes.
836
837=head2 How do I sort a hash (optionally by value instead of key)?
838
839Internally, hashes are stored in a way that prevents you from imposing
840an order on key-value pairs. Instead, you have to sort a list of the
841keys or values:
842
843 @keys = sort keys %hash; # sorted by key
844 @keys = sort {
845 $hash{$a} cmp $hash{$b}
846 } keys %hash; # and by value
847
848Here we'll do a reverse numeric sort by value, and if two keys are
849identical, sort by length of key, and if that fails, by straight ASCII
850comparison of the keys (well, possibly modified by your locale -- see
851L<perllocale>).
852
853 @keys = sort {
854 $hash{$b} <=> $hash{$a}
855 ||
856 length($b) <=> length($a)
857 ||
858 $a cmp $b
859 } keys %hash;
860
861=head2 How can I always keep my hash sorted?
862
863You can look into using the DB_File module and tie() using the
864$DB_BTREE hash bindings as documented in L<DB_File/"In Memory Databases">.
865
866=head2 What's the difference between "delete" and "undef" with hashes?
867
868Hashes are pairs of scalars: the first is the key, the second is the
869value. The key will be coerced to a string, although the value can be
870any kind of scalar: string, number, or reference. If a key C<$key> is
871present in the array, C<exists($key)> will return true. The value for
872a given key can be C<undef>, in which case C<$array{$key}> will be
873C<undef> while C<$exists{$key}> will return true. This corresponds to
874(C<$key>, C<undef>) being in the hash.
875
876Pictures help... here's the C<%ary> table:
877
878 keys values
879 +------+------+
880 | a | 3 |
881 | x | 7 |
882 | d | 0 |
883 | e | 2 |
884 +------+------+
885
886And these conditions hold
887
888 $ary{'a'} is true
889 $ary{'d'} is false
890 defined $ary{'d'} is true
891 defined $ary{'a'} is true
892 exists $ary{'a'} is true (perl5 only)
893 grep ($_ eq 'a', keys %ary) is true
894
895If you now say
896
897 undef $ary{'a'}
898
899your table now reads:
900
901
902 keys values
903 +------+------+
904 | a | undef|
905 | x | 7 |
906 | d | 0 |
907 | e | 2 |
908 +------+------+
909
910and these conditions now hold; changes in caps:
911
912 $ary{'a'} is FALSE
913 $ary{'d'} is false
914 defined $ary{'d'} is true
915 defined $ary{'a'} is FALSE
916 exists $ary{'a'} is true (perl5 only)
917 grep ($_ eq 'a', keys %ary) is true
918
919Notice the last two: you have an undef value, but a defined key!
920
921Now, consider this:
922
923 delete $ary{'a'}
924
925your table now reads:
926
927 keys values
928 +------+------+
929 | x | 7 |
930 | d | 0 |
931 | e | 2 |
932 +------+------+
933
934and these conditions now hold; changes in caps:
935
936 $ary{'a'} is false
937 $ary{'d'} is false
938 defined $ary{'d'} is true
939 defined $ary{'a'} is false
940 exists $ary{'a'} is FALSE (perl5 only)
941 grep ($_ eq 'a', keys %ary) is FALSE
942
943See, the whole entry is gone!
944
945=head2 Why don't my tied hashes make the defined/exists distinction?
946
947They may or may not implement the EXISTS() and DEFINED() methods
948differently. For example, there isn't the concept of undef with hashes
949that are tied to DBM* files. This means the true/false tables above
950will give different results when used on such a hash. It also means
951that exists and defined do the same thing with a DBM* file, and what
952they end up doing is not what they do with ordinary hashes.
953
954=head2 How do I reset an each() operation part-way through?
955
956Using C<keys %hash> in a scalar context returns the number of keys in
957the hash I<and> resets the iterator associated with the hash. You may
958need to do this if you use C<last> to exit a loop early so that when you
46fc3d4c 959re-enter it, the hash iterator has been reset.
68dc0745 960
961=head2 How can I get the unique keys from two hashes?
962
963First you extract the keys from the hashes into arrays, and then solve
964the uniquifying the array problem described above. For example:
965
966 %seen = ();
967 for $element (keys(%foo), keys(%bar)) {
968 $seen{$element}++;
969 }
970 @uniq = keys %seen;
971
972Or more succinctly:
973
974 @uniq = keys %{{%foo,%bar}};
975
976Or if you really want to save space:
977
978 %seen = ();
979 while (defined ($key = each %foo)) {
980 $seen{$key}++;
981 }
982 while (defined ($key = each %bar)) {
983 $seen{$key}++;
984 }
985 @uniq = keys %seen;
986
987=head2 How can I store a multidimensional array in a DBM file?
988
989Either stringify the structure yourself (no fun), or else
990get the MLDBM (which uses Data::Dumper) module from CPAN and layer
991it on top of either DB_File or GDBM_File.
992
993=head2 How can I make my hash remember the order I put elements into it?
994
995Use the Tie::IxHash from CPAN.
996
46fc3d4c 997 use Tie::IxHash;
998 tie(%myhash, Tie::IxHash);
999 for ($i=0; $i<20; $i++) {
1000 $myhash{$i} = 2*$i;
1001 }
1002 @keys = keys %myhash;
1003 # @keys = (0,1,2,3,...)
1004
68dc0745 1005=head2 Why does passing a subroutine an undefined element in a hash create it?
1006
1007If you say something like:
1008
1009 somefunc($hash{"nonesuch key here"});
1010
1011Then that element "autovivifies"; that is, it springs into existence
1012whether you store something there or not. That's because functions
1013get scalars passed in by reference. If somefunc() modifies C<$_[0]>,
1014it has to be ready to write it back into the caller's version.
1015
1016This has been fixed as of perl5.004.
1017
1018Normally, merely accessing a key's value for a nonexistent key does
1019I<not> cause that key to be forever there. This is different than
1020awk's behavior.
1021
54310121 1022=head2 How can I make the Perl equivalent of a C structure/C++ class/hash
68dc0745 1023or array of hashes or arrays?
1024
1025Use references (documented in L<perlref>). Examples of complex data
1026structures are given in L<perldsc> and L<perllol>. Examples of
1027structures and object-oriented classes are in L<perltoot>.
1028
1029=head2 How can I use a reference as a hash key?
1030
1031You can't do this directly, but you could use the standard Tie::Refhash
1032module distributed with perl.
1033
1034=head1 Data: Misc
1035
1036=head2 How do I handle binary data correctly?
1037
1038Perl is binary clean, so this shouldn't be a problem. For example,
1039this works fine (assuming the files are found):
1040
1041 if (`cat /vmunix` =~ /gzip/) {
1042 print "Your kernel is GNU-zip enabled!\n";
1043 }
1044
1045On some systems, however, you have to play tedious games with "text"
1046versus "binary" files. See L<perlfunc/"binmode">.
1047
1048If you're concerned about 8-bit ASCII data, then see L<perllocale>.
1049
54310121 1050If you want to deal with multibyte characters, however, there are
68dc0745 1051some gotchas. See the section on Regular Expressions.
1052
1053=head2 How do I determine whether a scalar is a number/whole/integer/float?
1054
1055Assuming that you don't care about IEEE notations like "NaN" or
1056"Infinity", you probably just want to use a regular expression.
1057
1058 warn "has nondigits" if /\D/;
1059 warn "not a whole number" unless /^\d+$/;
1060 warn "not an integer" unless /^-?\d+$/; # reject +3
54310121 1061 warn "not an integer" unless /^[+-]?\d+$/;
68dc0745 1062 warn "not a decimal number" unless /^-?\d+\.?\d*$/; # rejects .2
1063 warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
1064 warn "not a C float"
1065 unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
1066
1067Or you could check out
1068http://www.perl.com/CPAN/modules/by-module/String/String-Scanf-1.1.tar.gz
1069instead. The POSIX module (part of the standard Perl distribution)
1070provides the C<strtol> and C<strtod> for converting strings to double
1071and longs, respectively.
1072
1073=head2 How do I keep persistent data across program calls?
1074
1075For some specific applications, you can use one of the DBM modules.
1076See L<AnyDBM_File>. More generically, you should consult the
1077FreezeThaw, Storable, or Class::Eroot modules from CPAN.
1078
1079=head2 How do I print out or copy a recursive data structure?
1080
1081The Data::Dumper module on CPAN is nice for printing out
1082data structures, and FreezeThaw for copying them. For example:
1083
1084 use FreezeThaw qw(freeze thaw);
1085 $new = thaw freeze $old;
1086
1087Where $old can be (a reference to) any kind of data structure you'd like.
1088It will be deeply copied.
1089
1090=head2 How do I define methods for every class/object?
1091
1092Use the UNIVERSAL class (see L<UNIVERSAL>).
1093
1094=head2 How do I verify a credit card checksum?
1095
1096Get the Business::CreditCard module from CPAN.
1097
1098=head1 AUTHOR AND COPYRIGHT
1099
1100Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
1101All rights reserved. See L<perlfaq> for distribution information.
46fc3d4c 1102