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