Commit | Line | Data |
68dc0745 |
1 | =head1 NAME |
2 | |
3fe9a6f1 |
3 | perlfaq4 - Data Manipulation ($Revision: 1.17 $, $Date: 1997/03/25 18:16:24 $) |
68dc0745 |
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" |
3fe9a6f1 |
257 | into "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 | |
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//); |
54310121 |
274 | print "There are $count X characters in the string"; |
68dc0745 |
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: |
3fe9a6f1 |
289 | |
68dc0745 |
290 | $line =~ s/\b(\w)/\U$1/g; |
291 | |
292 | To make the whole line upper case: |
3fe9a6f1 |
293 | |
68dc0745 |
294 | $line = uc($line); |
295 | |
296 | To 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 | |
303 | Take the example case of trying to split a string that is comma-separated |
304 | into its different fields. (We'll pretend you said comma-separated, not |
305 | comma-delimited, which is different and almost never what you mean.) You |
306 | can't use C<split(/,/)> because you shouldn't split if the comma is inside |
307 | quotes. For example, take a data line like this: |
308 | |
309 | SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped" |
310 | |
311 | Due to the restriction of the quotes, this is a fairly complex |
312 | problem. Thankfully, we have Jeffrey Friedl, author of a highly |
313 | recommended book on regular expressions, to handle these for us. He |
314 | suggests (assuming your string is contained in $text): |
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 | |
324 | Alternatively, the Text::ParseWords module (part of the standard perl |
325 | distribution) 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 | |
332 | The simplest approach, albeit not the fastest, is probably like this: |
333 | |
334 | $string =~ s/^\s*(.*?)\s*$/$1/; |
335 | |
336 | It would be faster to do this in two steps: |
337 | |
338 | $string =~ s/^\s+//; |
339 | $string =~ s/\s+$//; |
340 | |
341 | Or 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 | |
350 | Use substr() or unpack(), both documented in L<perlfunc>. |
351 | |
352 | =head2 How do I find the soundex value of a string? |
353 | |
354 | Use the standard Text::Soundex module distributed with perl. |
355 | |
356 | =head2 How can I expand variables in text strings? |
357 | |
358 | Let'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 | |
363 | Before version 5 of perl, this had to be done with a double-eval |
364 | substitution: |
365 | |
366 | $text =~ s/(\$\w+)/$1/eeg; |
367 | |
368 | Which is bizarre enough that you'll probably actually need an EEG |
369 | afterwards. :-) |
370 | |
371 | =head2 What's wrong with always quoting "$vars"? |
372 | |
373 | The problem is that those double-quotes force stringification, |
374 | coercing numbers and references into strings, even when you |
375 | don't want them to be. |
376 | |
377 | If you get used to writing odd things like these: |
378 | |
379 | print "$var"; # BAD |
380 | $new = "$old"; # BAD |
381 | somefunc("$var"); # BAD |
382 | |
383 | You'll be in trouble. Those should (in 99.8% of the cases) be |
384 | the simpler and more direct: |
385 | |
386 | print $var; |
387 | $new = $old; |
388 | somefunc($var); |
389 | |
390 | Otherwise, besides slowing you down, you're going to break code when |
391 | the thing in the scalar is actually neither a string nor a number, but |
392 | a reference: |
393 | |
394 | func(\@array); |
395 | sub func { |
396 | my $aref = shift; |
397 | my $oref = "$aref"; # WRONG |
398 | } |
399 | |
400 | You can also get into subtle problems on those few operations in Perl |
401 | that actually do care about the difference between a string and a |
402 | number, such as the magical C<++> autoincrement operator or the |
403 | syscall() function. |
404 | |
405 | =head2 Why don't my <<HERE documents work? |
406 | |
407 | Check 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 | |
423 | The former is a scalar value, the latter an array slice, which makes |
424 | it a list with one (scalar) value. You should use $ when you want a |
425 | scalar value (most of the time) and @ when you want a list with one |
426 | scalar value in it (very, very rarely; nearly never, in fact). |
427 | |
428 | Sometimes it doesn't make a difference, but sometimes it does. |
429 | For example, compare: |
430 | |
431 | $good[0] = `some program that outputs several lines`; |
432 | |
433 | with |
434 | |
435 | @bad[0] = `same program that outputs several lines`; |
436 | |
437 | The B<-w> flag will warn you about these matters. |
438 | |
439 | =head2 How can I extract just the unique elements of an array? |
440 | |
441 | There are several possible ways, depending on whether the array is |
442 | ordered 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 | |
451 | This is nice in that it doesn't use much extra memory, |
452 | simulating uniq(1)'s behavior of removing only adjacent |
453 | duplicates. |
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 | |
480 | There are several ways to approach this. If you are going to make |
481 | this query many times and the values are arbitrary strings, the |
482 | fastest way is probably to invert the original array and keep an |
483 | associative array lying about whose keys are the first array's values. |
484 | |
485 | @blues = qw/azure cerulean teal turquoise lapis-lazuli/; |
486 | undef %is_blue; |
487 | for (@blues) { $is_blue{$_} = 1 } |
488 | |
489 | Now you can check whether $is_blue{$some_color}. It might have been a |
490 | good idea to keep the blues all in a hash in the first place. |
491 | |
492 | If the values are all small integers, you could use a simple indexed |
493 | array. This kind of an array will take up less space: |
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 | |
499 | Now you check whether $is_tiny_prime[$some_number]. |
500 | |
501 | If the values in question are integers instead of strings, you can save |
502 | quite a lot of space by using bit strings instead: |
503 | |
504 | @articles = ( 1..10, 150..2000, 2017 ); |
505 | undef $read; |
506 | grep (vec($read,$_,1) = 1, @articles); |
507 | |
508 | Now check whether C<vec($read,$n,1)> is true for some C<$n>. |
509 | |
510 | Please do not use |
511 | |
512 | $is_there = grep $_ eq $whatever, @array; |
513 | |
514 | or worse yet |
515 | |
516 | $is_there = grep /$whatever/, @array; |
517 | |
518 | These are slow (checks every element even if the first matches), |
519 | inefficient (same reason), and potentially buggy (what if there are |
520 | regexp characters in $whatever?). |
521 | |
522 | =head2 How do I compute the difference of two arrays? How do I compute the intersection of two arrays? |
523 | |
524 | Use a hash. Here's code to do both and more. It assumes that |
525 | each 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 | |
537 | You 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 | |
546 | Now C<$found_index> has what you want. |
547 | |
548 | =head2 How do I handle linked lists? |
549 | |
550 | In general, you usually don't need a linked list in Perl, since with |
551 | regular arrays, you can push and pop or shift and unshift at either end, |
552 | or you can use splice to add and/or remove arbitrary number of elements |
553 | at arbitrary points. |
554 | |
555 | If you really, really wanted, you could use structures as described in |
556 | L<perldsc> or L<perltoot> and do just what the algorithm book tells you |
557 | to do. |
558 | |
559 | =head2 How do I handle circular lists? |
560 | |
561 | Circular lists could be handled in the traditional fashion with linked |
562 | lists, or you could just do something like this with an array: |
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 | |
569 | Here's a shuffling algorithm which works its way through the list, |
570 | randomly 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 | |
579 | For 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 | |
592 | Use C<for>/C<foreach>: |
593 | |
594 | for (@lines) { |
595 | s/foo/bar/; |
596 | tr[a-z][A-Z]; |
597 | } |
598 | |
599 | Here'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 | |
608 | Use 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 | |
616 | Here's a little program that generates all permutations |
617 | of all the words on each line of input. The algorithm embodied |
618 | in the permut() function should work on any list: |
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 | |
644 | Supply a comparison function to sort() (described in L<perlfunc/sort>): |
645 | |
646 | @list = sort { $a <=> $b } @list; |
647 | |
648 | The default sort function is cmp, string comparison, which would |
649 | sort C<(1, 2, 10)> into C<(1, 10, 2)>. C<E<lt>=E<gt>>, used above, is |
650 | the numerical comparison operator. |
651 | |
652 | If you have a complicated function needed to pull out the part you |
653 | want to sort on, then don't do it inside the sort function. Pull it |
654 | out first, because the sort BLOCK can be called many times for the |
655 | same element. Here's an example of how to pull out the first word |
656 | after the first number on each item, and then sort those words |
657 | case-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 | |
666 | Which could also be written this way, using a trick |
667 | that'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 | |
673 | If 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 | |
680 | This can be conveniently combined with precalculation of keys as given |
681 | above. |
682 | |
683 | See http://www.perl.com/CPAN/doc/FMTEYEWTK/sort.html for more about |
684 | this approach. |
685 | |
686 | See also the question below on sorting hashes. |
687 | |
688 | =head2 How do I manipulate arrays of bits? |
689 | |
690 | Use pack() and unpack(), or else vec() and the bitwise operations. |
691 | |
692 | For 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 | |
697 | And here's how, given a vector in $vec, you can |
698 | get 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 | |
729 | This 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 | |
734 | See 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 | |
740 | Use the each() function (see L<perlfunc/each>) if you don't care |
741 | whether it's sorted: |
742 | |
743 | while (($key,$value) = each %hash) { |
744 | print "$key = $value\n"; |
745 | } |
746 | |
747 | If you want it sorted, you'll have to use foreach() on the result of |
748 | sorting the keys as shown in an earlier question. |
749 | |
750 | =head2 What happens if I add or remove keys from a hash while iterating over it? |
751 | |
752 | Don't do that. |
753 | |
754 | =head2 How do I look up a hash element by value? |
755 | |
756 | Create a reverse hash: |
757 | |
758 | %by_value = reverse %by_key; |
759 | $key = $by_value{$value}; |
760 | |
761 | That's not particularly efficient. It would be more space-efficient |
762 | to use: |
763 | |
764 | while (($key, $value) = each %by_key) { |
765 | $by_value{$value} = $key; |
766 | } |
767 | |
768 | If your hash could have repeated values, the methods above will only |
769 | find one of the associated keys. This may or may not worry you. |
770 | |
771 | =head2 How can I know how many entries are in a hash? |
772 | |
773 | If you mean how many keys, then all you have to do is |
774 | take the scalar sense of the keys() function: |
775 | |
3fe9a6f1 |
776 | $num_keys = scalar keys %hash; |
68dc0745 |
777 | |
778 | In void context it just resets the iterator, which is faster |
779 | for tied hashes. |
780 | |
781 | =head2 How do I sort a hash (optionally by value instead of key)? |
782 | |
783 | Internally, hashes are stored in a way that prevents you from imposing |
784 | an order on key-value pairs. Instead, you have to sort a list of the |
785 | keys 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 | |
792 | Here we'll do a reverse numeric sort by value, and if two keys are |
793 | identical, sort by length of key, and if that fails, by straight ASCII |
794 | comparison of the keys (well, possibly modified by your locale -- see |
795 | L<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 | |
807 | You can look into using the DB_File module and tie() using the |
808 | $DB_BTREE hash bindings as documented in L<DB_File/"In Memory Databases">. |
809 | |
810 | =head2 What's the difference between "delete" and "undef" with hashes? |
811 | |
812 | Hashes are pairs of scalars: the first is the key, the second is the |
813 | value. The key will be coerced to a string, although the value can be |
814 | any kind of scalar: string, number, or reference. If a key C<$key> is |
815 | present in the array, C<exists($key)> will return true. The value for |
816 | a given key can be C<undef>, in which case C<$array{$key}> will be |
817 | C<undef> while C<$exists{$key}> will return true. This corresponds to |
818 | (C<$key>, C<undef>) being in the hash. |
819 | |
820 | Pictures 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 | |
830 | And 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 | |
839 | If you now say |
840 | |
841 | undef $ary{'a'} |
842 | |
843 | your table now reads: |
844 | |
845 | |
846 | keys values |
847 | +------+------+ |
848 | | a | undef| |
849 | | x | 7 | |
850 | | d | 0 | |
851 | | e | 2 | |
852 | +------+------+ |
853 | |
854 | and 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 | |
863 | Notice the last two: you have an undef value, but a defined key! |
864 | |
865 | Now, consider this: |
866 | |
867 | delete $ary{'a'} |
868 | |
869 | your table now reads: |
870 | |
871 | keys values |
872 | +------+------+ |
873 | | x | 7 | |
874 | | d | 0 | |
875 | | e | 2 | |
876 | +------+------+ |
877 | |
878 | and 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 | |
887 | See, the whole entry is gone! |
888 | |
889 | =head2 Why don't my tied hashes make the defined/exists distinction? |
890 | |
891 | They may or may not implement the EXISTS() and DEFINED() methods |
892 | differently. For example, there isn't the concept of undef with hashes |
893 | that are tied to DBM* files. This means the true/false tables above |
894 | will give different results when used on such a hash. It also means |
895 | that exists and defined do the same thing with a DBM* file, and what |
896 | they end up doing is not what they do with ordinary hashes. |
897 | |
898 | =head2 How do I reset an each() operation part-way through? |
899 | |
900 | Using C<keys %hash> in a scalar context returns the number of keys in |
901 | the hash I<and> resets the iterator associated with the hash. You may |
902 | need to do this if you use C<last> to exit a loop early so that when you |
54310121 |
903 | reenter it, the hash iterator has been reset. |
68dc0745 |
904 | |
905 | =head2 How can I get the unique keys from two hashes? |
906 | |
907 | First you extract the keys from the hashes into arrays, and then solve |
908 | the 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 | |
916 | Or more succinctly: |
917 | |
918 | @uniq = keys %{{%foo,%bar}}; |
919 | |
920 | Or 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 | |
933 | Either stringify the structure yourself (no fun), or else |
934 | get the MLDBM (which uses Data::Dumper) module from CPAN and layer |
935 | it on top of either DB_File or GDBM_File. |
936 | |
937 | =head2 How can I make my hash remember the order I put elements into it? |
938 | |
939 | Use the Tie::IxHash from CPAN. |
940 | |
941 | =head2 Why does passing a subroutine an undefined element in a hash create it? |
942 | |
943 | If you say something like: |
944 | |
945 | somefunc($hash{"nonesuch key here"}); |
946 | |
947 | Then that element "autovivifies"; that is, it springs into existence |
948 | whether you store something there or not. That's because functions |
949 | get scalars passed in by reference. If somefunc() modifies C<$_[0]>, |
950 | it has to be ready to write it back into the caller's version. |
951 | |
952 | This has been fixed as of perl5.004. |
953 | |
954 | Normally, merely accessing a key's value for a nonexistent key does |
955 | I<not> cause that key to be forever there. This is different than |
956 | awk's behavior. |
957 | |
54310121 |
958 | =head2 How can I make the Perl equivalent of a C structure/C++ class/hash |
68dc0745 |
959 | or array of hashes or arrays? |
960 | |
961 | Use references (documented in L<perlref>). Examples of complex data |
962 | structures are given in L<perldsc> and L<perllol>. Examples of |
963 | structures and object-oriented classes are in L<perltoot>. |
964 | |
965 | =head2 How can I use a reference as a hash key? |
966 | |
967 | You can't do this directly, but you could use the standard Tie::Refhash |
968 | module distributed with perl. |
969 | |
970 | =head1 Data: Misc |
971 | |
972 | =head2 How do I handle binary data correctly? |
973 | |
974 | Perl is binary clean, so this shouldn't be a problem. For example, |
975 | this works fine (assuming the files are found): |
976 | |
977 | if (`cat /vmunix` =~ /gzip/) { |
978 | print "Your kernel is GNU-zip enabled!\n"; |
979 | } |
980 | |
981 | On some systems, however, you have to play tedious games with "text" |
982 | versus "binary" files. See L<perlfunc/"binmode">. |
983 | |
984 | If you're concerned about 8-bit ASCII data, then see L<perllocale>. |
985 | |
54310121 |
986 | If you want to deal with multibyte characters, however, there are |
68dc0745 |
987 | some gotchas. See the section on Regular Expressions. |
988 | |
989 | =head2 How do I determine whether a scalar is a number/whole/integer/float? |
990 | |
991 | Assuming 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 | |
1003 | Or you could check out |
1004 | http://www.perl.com/CPAN/modules/by-module/String/String-Scanf-1.1.tar.gz |
1005 | instead. The POSIX module (part of the standard Perl distribution) |
1006 | provides the C<strtol> and C<strtod> for converting strings to double |
1007 | and longs, respectively. |
1008 | |
1009 | =head2 How do I keep persistent data across program calls? |
1010 | |
1011 | For some specific applications, you can use one of the DBM modules. |
1012 | See L<AnyDBM_File>. More generically, you should consult the |
1013 | FreezeThaw, Storable, or Class::Eroot modules from CPAN. |
1014 | |
1015 | =head2 How do I print out or copy a recursive data structure? |
1016 | |
1017 | The Data::Dumper module on CPAN is nice for printing out |
1018 | data structures, and FreezeThaw for copying them. For example: |
1019 | |
1020 | use FreezeThaw qw(freeze thaw); |
1021 | $new = thaw freeze $old; |
1022 | |
1023 | Where $old can be (a reference to) any kind of data structure you'd like. |
1024 | It will be deeply copied. |
1025 | |
1026 | =head2 How do I define methods for every class/object? |
1027 | |
1028 | Use the UNIVERSAL class (see L<UNIVERSAL>). |
1029 | |
1030 | =head2 How do I verify a credit card checksum? |
1031 | |
1032 | Get the Business::CreditCard module from CPAN. |
1033 | |
1034 | =head1 AUTHOR AND COPYRIGHT |
1035 | |
1036 | Copyright (c) 1997 Tom Christiansen and Nathan Torkington. |
1037 | All rights reserved. See L<perlfaq> for distribution information. |