This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Missed OS/2 patch hunk.
[perl5.git] / pod / perlfaq4.pod
CommitLineData
68dc0745 1=head1 NAME
2
369b44b4 3perlfaq4 - Data Manipulation ($Revision: 1.44 $, $Date: 2003/07/28 17:35:21 $)
68dc0745 4
5=head1 DESCRIPTION
6
ae3d0b9f
JH
7This section of the FAQ answers questions related to manipulating
8numbers, dates, strings, arrays, hashes, and miscellaneous data issues.
68dc0745 9
10=head1 Data: Numbers
11
46fc3d4c 12=head2 Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?
13
49d635f9
RGS
14Internally, your computer represents floating-point numbers
15in binary. Digital (as in powers of two) computers cannot
16store all numbers exactly. Some real numbers lose precision
17in the process. This is a problem with how computers store
18numbers and affects all computer languages, not just Perl.
46fc3d4c 19
49d635f9
RGS
20L<perlnumber> show the gory details of number
21representations and conversions.
22
23To limit the number of decimal places in your numbers, you
24can use the printf or sprintf function. See the
197aec24 25L<"Floating Point Arithmetic"|perlop> for more details.
49d635f9
RGS
26
27 printf "%.2f", 10/3;
197aec24 28
49d635f9 29 my $number = sprintf "%.2f", 10/3;
197aec24 30
32969b6e
BB
31=head2 Why is int() broken?
32
33Your int() is most probably working just fine. It's the numbers that
34aren't quite what you think.
35
36First, see the above item "Why am I getting long decimals
37(eg, 19.9499999999999) instead of the numbers I should be getting
38(eg, 19.95)?".
39
40For example, this
41
42 print int(0.6/0.2-2), "\n";
43
44will in most computers print 0, not 1, because even such simple
45numbers as 0.6 and 0.2 cannot be presented exactly by floating-point
46numbers. What you think in the above as 'three' is really more like
472.9999999999999995559.
48
68dc0745 49=head2 Why isn't my octal data interpreted correctly?
50
49d635f9
RGS
51Perl only understands octal and hex numbers as such when they occur as
52literals in your program. Octal literals in perl must start with a
53leading "0" and hexadecimal literals must start with a leading "0x".
54If they are read in from somewhere and assigned, no automatic
55conversion takes place. You must explicitly use oct() or hex() if you
56want the values converted to decimal. oct() interprets hex ("0x350"),
57octal ("0350" or even without the leading "0", like "377") and binary
58("0b1010") numbers, while hex() only converts hexadecimal ones, with
59or without a leading "0x", like "0x255", "3A", "ff", or "deadbeef".
33ce146f 60The inverse mapping from decimal to octal can be done with either the
49d635f9 61"%o" or "%O" sprintf() formats.
68dc0745 62
63This problem shows up most often when people try using chmod(), mkdir(),
197aec24 64umask(), or sysopen(), which by widespread tradition typically take
33ce146f 65permissions in octal.
68dc0745 66
33ce146f 67 chmod(644, $file); # WRONG
68dc0745 68 chmod(0644, $file); # right
69
197aec24 70Note the mistake in the first line was specifying the decimal literal
33ce146f
PP
71644, rather than the intended octal literal 0644. The problem can
72be seen with:
73
434f7166 74 printf("%#o",644); # prints 01204
33ce146f
PP
75
76Surely you had not intended C<chmod(01204, $file);> - did you? If you
77want to use numeric literals as arguments to chmod() et al. then please
197aec24 78try to express them as octal constants, that is with a leading zero and
33ce146f
PP
79with the following digits restricted to the set 0..7.
80
65acb1b1 81=head2 Does Perl have a round() function? What about ceil() and floor()? Trig functions?
68dc0745 82
92c2ed05
GS
83Remember that int() merely truncates toward 0. For rounding to a
84certain number of digits, sprintf() or printf() is usually the easiest
85route.
86
87 printf("%.3f", 3.1415926535); # prints 3.142
68dc0745 88
87275199 89The POSIX module (part of the standard Perl distribution) implements
68dc0745 90ceil(), floor(), and a number of other mathematical and trigonometric
91functions.
92
92c2ed05
GS
93 use POSIX;
94 $ceil = ceil(3.5); # 4
95 $floor = floor(3.5); # 3
96
a6dd486b 97In 5.000 to 5.003 perls, trigonometry was done in the Math::Complex
87275199 98module. With 5.004, the Math::Trig module (part of the standard Perl
46fc3d4c 99distribution) implements the trigonometric functions. Internally it
100uses the Math::Complex module and some functions can break out from
101the real axis into the complex plane, for example the inverse sine of
1022.
68dc0745 103
104Rounding in financial applications can have serious implications, and
105the rounding method used should be specified precisely. In these
106cases, it probably pays not to trust whichever system rounding is
107being used by Perl, but to instead implement the rounding function you
108need yourself.
109
65acb1b1
TC
110To see why, notice how you'll still have an issue on half-way-point
111alternation:
112
113 for ($i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i}
114
197aec24 115 0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7
65acb1b1
TC
116 0.8 0.8 0.9 0.9 1.0 1.0
117
118Don't blame Perl. It's the same as in C. IEEE says we have to do this.
119Perl numbers whose absolute values are integers under 2**31 (on 32 bit
120machines) will work pretty much like mathematical integers. Other numbers
121are not guaranteed.
122
ae3d0b9f 123=head2 How do I convert between numeric representations?
68dc0745 124
6761e064
JH
125As always with Perl there is more than one way to do it. Below
126are a few examples of approaches to making common conversions
127between number representations. This is intended to be representational
128rather than exhaustive.
68dc0745 129
6761e064
JH
130Some of the examples below use the Bit::Vector module from CPAN.
131The reason you might choose Bit::Vector over the perl built in
132functions is that it works with numbers of ANY size, that it is
133optimized for speed on some operations, and for at least some
134programmers the notation might be familiar.
d92eb7b0 135
818c4caa
JH
136=over 4
137
138=item How do I convert hexadecimal into decimal
d92eb7b0 139
6761e064
JH
140Using perl's built in conversion of 0x notation:
141
142 $int = 0xDEADBEEF;
143 $dec = sprintf("%d", $int);
7207e29d 144
6761e064
JH
145Using the hex function:
146
147 $int = hex("DEADBEEF");
148 $dec = sprintf("%d", $int);
149
150Using pack:
151
152 $int = unpack("N", pack("H8", substr("0" x 8 . "DEADBEEF", -8)));
153 $dec = sprintf("%d", $int);
154
155Using the CPAN module Bit::Vector:
156
157 use Bit::Vector;
158 $vec = Bit::Vector->new_Hex(32, "DEADBEEF");
159 $dec = $vec->to_Dec();
160
818c4caa 161=item How do I convert from decimal to hexadecimal
6761e064 162
04d666b1 163Using sprintf:
6761e064
JH
164
165 $hex = sprintf("%X", 3735928559);
166
167Using unpack
168
169 $hex = unpack("H*", pack("N", 3735928559));
170
171Using Bit::Vector
172
173 use Bit::Vector;
174 $vec = Bit::Vector->new_Dec(32, -559038737);
175 $hex = $vec->to_Hex();
176
177And Bit::Vector supports odd bit counts:
178
179 use Bit::Vector;
180 $vec = Bit::Vector->new_Dec(33, 3735928559);
181 $vec->Resize(32); # suppress leading 0 if unwanted
182 $hex = $vec->to_Hex();
183
818c4caa 184=item How do I convert from octal to decimal
6761e064
JH
185
186Using Perl's built in conversion of numbers with leading zeros:
187
188 $int = 033653337357; # note the leading 0!
189 $dec = sprintf("%d", $int);
190
191Using the oct function:
192
193 $int = oct("33653337357");
194 $dec = sprintf("%d", $int);
195
196Using Bit::Vector:
197
198 use Bit::Vector;
199 $vec = Bit::Vector->new(32);
200 $vec->Chunk_List_Store(3, split(//, reverse "33653337357"));
201 $dec = $vec->to_Dec();
202
818c4caa 203=item How do I convert from decimal to octal
6761e064
JH
204
205Using sprintf:
206
207 $oct = sprintf("%o", 3735928559);
208
209Using Bit::Vector
210
211 use Bit::Vector;
212 $vec = Bit::Vector->new_Dec(32, -559038737);
213 $oct = reverse join('', $vec->Chunk_List_Read(3));
214
818c4caa 215=item How do I convert from binary to decimal
6761e064 216
2c646907
JH
217Perl 5.6 lets you write binary numbers directly with
218the 0b notation:
219
220 $number = 0b10110110;
221
6761e064 222Using pack and ord
d92eb7b0
GS
223
224 $decimal = ord(pack('B8', '10110110'));
68dc0745 225
6761e064
JH
226Using pack and unpack for larger strings
227
228 $int = unpack("N", pack("B32",
229 substr("0" x 32 . "11110101011011011111011101111", -32)));
230 $dec = sprintf("%d", $int);
231
5efd7060 232 # substr() is used to left pad a 32 character string with zeros.
6761e064
JH
233
234Using Bit::Vector:
235
236 $vec = Bit::Vector->new_Bin(32, "11011110101011011011111011101111");
237 $dec = $vec->to_Dec();
238
818c4caa 239=item How do I convert from decimal to binary
6761e064
JH
240
241Using unpack;
242
243 $bin = unpack("B*", pack("N", 3735928559));
244
245Using Bit::Vector:
246
247 use Bit::Vector;
248 $vec = Bit::Vector->new_Dec(32, -559038737);
249 $bin = $vec->to_Bin();
250
251The remaining transformations (e.g. hex -> oct, bin -> hex, etc.)
252are left as an exercise to the inclined reader.
68dc0745 253
818c4caa 254=back
68dc0745 255
65acb1b1
TC
256=head2 Why doesn't & work the way I want it to?
257
258The behavior of binary arithmetic operators depends on whether they're
259used on numbers or strings. The operators treat a string as a series
260of bits and work with that (the string C<"3"> is the bit pattern
261C<00110011>). The operators work with the binary form of a number
262(the number C<3> is treated as the bit pattern C<00000011>).
263
264So, saying C<11 & 3> performs the "and" operation on numbers (yielding
49d635f9 265C<3>). Saying C<"11" & "3"> performs the "and" operation on strings
65acb1b1
TC
266(yielding C<"1">).
267
268Most problems with C<&> and C<|> arise because the programmer thinks
269they have a number but really it's a string. The rest arise because
270the programmer says:
271
272 if ("\020\020" & "\101\101") {
273 # ...
274 }
275
276but a string consisting of two null bytes (the result of C<"\020\020"
277& "\101\101">) is not a false value in Perl. You need:
278
279 if ( ("\020\020" & "\101\101") !~ /[^\000]/) {
280 # ...
281 }
282
68dc0745 283=head2 How do I multiply matrices?
284
285Use the Math::Matrix or Math::MatrixReal modules (available from CPAN)
286or the PDL extension (also available from CPAN).
287
288=head2 How do I perform an operation on a series of integers?
289
290To call a function on each element in an array, and collect the
291results, use:
292
293 @results = map { my_func($_) } @array;
294
295For example:
296
297 @triple = map { 3 * $_ } @single;
298
299To call a function on each element of an array, but ignore the
300results:
301
302 foreach $iterator (@array) {
65acb1b1 303 some_func($iterator);
68dc0745 304 }
305
306To call a function on each integer in a (small) range, you B<can> use:
307
65acb1b1 308 @results = map { some_func($_) } (5 .. 25);
68dc0745 309
310but you should be aware that the C<..> operator creates an array of
311all integers in the range. This can take a lot of memory for large
312ranges. Instead use:
313
314 @results = ();
315 for ($i=5; $i < 500_005; $i++) {
65acb1b1 316 push(@results, some_func($i));
68dc0745 317 }
318
87275199
GS
319This situation has been fixed in Perl5.005. Use of C<..> in a C<for>
320loop will iterate over the range, without creating the entire range.
321
322 for my $i (5 .. 500_005) {
323 push(@results, some_func($i));
324 }
325
326will not create a list of 500,000 integers.
327
68dc0745 328=head2 How can I output Roman numerals?
329
a93751fa 330Get the http://www.cpan.org/modules/by-module/Roman module.
68dc0745 331
332=head2 Why aren't my random numbers random?
333
65acb1b1
TC
334If you're using a version of Perl before 5.004, you must call C<srand>
335once at the start of your program to seed the random number generator.
49d635f9 336
5cd0b561 337 BEGIN { srand() if $] < 5.004 }
49d635f9 338
65acb1b1 3395.004 and later automatically call C<srand> at the beginning. Don't
49d635f9 340call C<srand> more than once---you make your numbers less random, rather
65acb1b1 341than more.
92c2ed05 342
65acb1b1 343Computers are good at being predictable and bad at being random
06a5f41f 344(despite appearances caused by bugs in your programs :-). see the
49d635f9
RGS
345F<random> article in the "Far More Than You Ever Wanted To Know"
346collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz , courtesy of
06a5f41f
JH
347Tom Phoenix, talks more about this. John von Neumann said, ``Anyone
348who attempts to generate random numbers by deterministic means is, of
65acb1b1
TC
349course, living in a state of sin.''
350
351If you want numbers that are more random than C<rand> with C<srand>
352provides, you should also check out the Math::TrulyRandom module from
353CPAN. It uses the imperfections in your system's timer to generate
354random numbers, but this takes quite a while. If you want a better
92c2ed05 355pseudorandom generator than comes with your operating system, look at
65acb1b1 356``Numerical Recipes in C'' at http://www.nr.com/ .
68dc0745 357
881bdbd4
JH
358=head2 How do I get a random number between X and Y?
359
360Use the following simple function. It selects a random integer between
361(and possibly including!) the two given integers, e.g.,
362C<random_int_in(50,120)>
363
364 sub random_int_in ($$) {
365 my($min, $max) = @_;
366 # Assumes that the two arguments are integers themselves!
367 return $min if $min == $max;
368 ($min, $max) = ($max, $min) if $min > $max;
369 return $min + int rand(1 + $max - $min);
370 }
371
68dc0745 372=head1 Data: Dates
373
5cd0b561 374=head2 How do I find the day or week of the year?
68dc0745 375
5cd0b561
RGS
376The localtime function returns the day of the week. Without an
377argument localtime uses the current time.
68dc0745 378
5cd0b561 379 $day_of_year = (localtime)[7];
ffc145e8 380
5cd0b561
RGS
381The POSIX module can also format a date as the day of the year or
382week of the year.
68dc0745 383
5cd0b561
RGS
384 use POSIX qw/strftime/;
385 my $day_of_year = strftime "%j", localtime;
386 my $week_of_year = strftime "%W", localtime;
387
388To get the day of year for any date, use the Time::Local module to get
389a time in epoch seconds for the argument to localtime.
ffc145e8 390
5cd0b561
RGS
391 use POSIX qw/strftime/;
392 use Time::Local;
393 my $week_of_year = strftime "%W",
394 localtime( timelocal( 0, 0, 0, 18, 11, 1987 ) );
395
396The Date::Calc module provides two functions for to calculate these.
397
398 use Date::Calc;
399 my $day_of_year = Day_of_Year( 1987, 12, 18 );
400 my $week_of_year = Week_of_Year( 1987, 12, 18 );
ffc145e8 401
d92eb7b0
GS
402=head2 How do I find the current century or millennium?
403
404Use the following simple functions:
405
197aec24 406 sub get_century {
d92eb7b0 407 return int((((localtime(shift || time))[5] + 1999))/100);
197aec24
RGS
408 }
409 sub get_millennium {
d92eb7b0 410 return 1+int((((localtime(shift || time))[5] + 1899))/1000);
197aec24 411 }
d92eb7b0 412
49d635f9
RGS
413You can also use the POSIX strftime() function which may be a bit
414slower but is easier to read and maintain.
415
416 use POSIX qw/strftime/;
197aec24 417
49d635f9
RGS
418 my $week_of_the_year = strftime "%W", localtime;
419 my $day_of_the_year = strftime "%j", localtime;
420
421On some systems, the POSIX module's strftime() function has
422been extended in a non-standard way to use a C<%C> format,
423which they sometimes claim is the "century". It isn't,
424because on most such systems, this is only the first two
425digits of the four-digit year, and thus cannot be used to
426reliably determine the current century or millennium.
d92eb7b0 427
92c2ed05 428=head2 How can I compare two dates and find the difference?
68dc0745 429
92c2ed05
GS
430If you're storing your dates as epoch seconds then simply subtract one
431from the other. If you've got a structured date (distinct year, day,
d92eb7b0
GS
432month, hour, minute, seconds values), then for reasons of accessibility,
433simplicity, and efficiency, merely use either timelocal or timegm (from
434the Time::Local module in the standard distribution) to reduce structured
435dates to epoch seconds. However, if you don't know the precise format of
436your dates, then you should probably use either of the Date::Manip and
437Date::Calc modules from CPAN before you go hacking up your own parsing
438routine to handle arbitrary date formats.
68dc0745 439
440=head2 How can I take a string and turn it into epoch seconds?
441
442If it's a regular enough string that it always has the same format,
92c2ed05
GS
443you can split it up and pass the parts to C<timelocal> in the standard
444Time::Local module. Otherwise, you should look into the Date::Calc
445and Date::Manip modules from CPAN.
68dc0745 446
447=head2 How can I find the Julian Day?
448
2a2bf5f4
JH
449Use the Time::JulianDay module (part of the Time-modules bundle
450available from CPAN.)
d92eb7b0 451
89435c96
MS
452Before you immerse yourself too deeply in this, be sure to verify that
453it is the I<Julian> Day you really want. Are you interested in a way
454of getting serial days so that you just can tell how many days they
455are apart or so that you can do also other date arithmetic? If you
d92eb7b0 456are interested in performing date arithmetic, this can be done using
2a2bf5f4 457modules Date::Manip or Date::Calc.
89435c96
MS
458
459There is too many details and much confusion on this issue to cover in
460this FAQ, but the term is applied (correctly) to a calendar now
461supplanted by the Gregorian Calendar, with the Julian Calendar failing
462to adjust properly for leap years on centennial years (among other
463annoyances). The term is also used (incorrectly) to mean: [1] days in
464the Gregorian Calendar; and [2] days since a particular starting time
465or `epoch', usually 1970 in the Unix world and 1980 in the
466MS-DOS/Windows world. If you find that it is not the first meaning
467that you really want, then check out the Date::Manip and Date::Calc
468modules. (Thanks to David Cassell for most of this text.)
be94a901 469
65acb1b1
TC
470=head2 How do I find yesterday's date?
471
49d635f9
RGS
472If you only need to find the date (and not the same time), you
473can use the Date::Calc module.
65acb1b1 474
49d635f9 475 use Date::Calc qw(Today Add_Delta_Days);
197aec24 476
49d635f9 477 my @date = Add_Delta_Days( Today(), -1 );
197aec24 478
49d635f9 479 print "@date\n";
65acb1b1 480
49d635f9
RGS
481Most people try to use the time rather than the calendar to
482figure out dates, but that assumes that your days are
483twenty-four hours each. For most people, there are two days
484a year when they aren't: the switch to and from summer time
485throws this off. Russ Allbery offers this solution.
d92eb7b0
GS
486
487 sub yesterday {
49d635f9
RGS
488 my $now = defined $_[0] ? $_[0] : time;
489 my $then = $now - 60 * 60 * 24;
490 my $ndst = (localtime $now)[8] > 0;
491 my $tdst = (localtime $then)[8] > 0;
492 $then - ($tdst - $ndst) * 60 * 60;
493 }
197aec24 494
49d635f9
RGS
495Should give you "this time yesterday" in seconds since epoch relative to
496the first argument or the current time if no argument is given and
497suitable for passing to localtime or whatever else you need to do with
498it. $ndst is whether we're currently in daylight savings time; $tdst is
499whether the point 24 hours ago was in daylight savings time. If $tdst
500and $ndst are the same, a boundary wasn't crossed, and the correction
501will subtract 0. If $tdst is 1 and $ndst is 0, subtract an hour more
502from yesterday's time since we gained an extra hour while going off
503daylight savings time. If $tdst is 0 and $ndst is 1, subtract a
504negative hour (add an hour) to yesterday's time since we lost an hour.
505
506All of this is because during those days when one switches off or onto
507DST, a "day" isn't 24 hours long; it's either 23 or 25.
508
509The explicit settings of $ndst and $tdst are necessary because localtime
510only says it returns the system tm struct, and the system tm struct at
511least on Solaris doesn't guarantee any particular positive value (like,
512say, 1) for isdst, just a positive value. And that value can
513potentially be negative, if DST information isn't available (this sub
514just treats those cases like no DST).
515
516Note that between 2am and 3am on the day after the time zone switches
517off daylight savings time, the exact hour of "yesterday" corresponding
518to the current hour is not clearly defined. Note also that if used
519between 2am and 3am the day after the change to daylight savings time,
520the result will be between 3am and 4am of the previous day; it's
521arguable whether this is correct.
522
523This sub does not attempt to deal with leap seconds (most things don't).
524
525
d92eb7b0 526
87275199 527=head2 Does Perl have a Year 2000 problem? Is Perl Y2K compliant?
68dc0745 528
65acb1b1
TC
529Short answer: No, Perl does not have a Year 2000 problem. Yes, Perl is
530Y2K compliant (whatever that means). The programmers you've hired to
531use it, however, probably are not.
532
533Long answer: The question belies a true understanding of the issue.
534Perl is just as Y2K compliant as your pencil--no more, and no less.
535Can you use your pencil to write a non-Y2K-compliant memo? Of course
536you can. Is that the pencil's fault? Of course it isn't.
92c2ed05 537
87275199 538The date and time functions supplied with Perl (gmtime and localtime)
65acb1b1
TC
539supply adequate information to determine the year well beyond 2000
540(2038 is when trouble strikes for 32-bit machines). The year returned
90fdbbb7 541by these functions when used in a list context is the year minus 1900.
65acb1b1
TC
542For years between 1910 and 1999 this I<happens> to be a 2-digit decimal
543number. To avoid the year 2000 problem simply do not treat the year as
544a 2-digit number. It isn't.
68dc0745 545
5a964f20 546When gmtime() and localtime() are used in scalar context they return
68dc0745 547a timestamp string that contains a fully-expanded year. For example,
548C<$timestamp = gmtime(1005613200)> sets $timestamp to "Tue Nov 13 01:00:00
5492001". There's no year 2000 problem here.
550
5a964f20
TC
551That doesn't mean that Perl can't be used to create non-Y2K compliant
552programs. It can. But so can your pencil. It's the fault of the user,
553not the language. At the risk of inflaming the NRA: ``Perl doesn't
554break Y2K, people do.'' See http://language.perl.com/news/y2k.html for
555a longer exposition.
556
68dc0745 557=head1 Data: Strings
558
559=head2 How do I validate input?
560
561The answer to this question is usually a regular expression, perhaps
5a964f20 562with auxiliary logic. See the more specific questions (numbers, mail
68dc0745 563addresses, etc.) for details.
564
565=head2 How do I unescape a string?
566
92c2ed05
GS
567It depends just what you mean by ``escape''. URL escapes are dealt
568with in L<perlfaq9>. Shell escapes with the backslash (C<\>)
a6dd486b 569character are removed with
68dc0745 570
571 s/\\(.)/$1/g;
572
92c2ed05 573This won't expand C<"\n"> or C<"\t"> or any other special escapes.
68dc0745 574
575=head2 How do I remove consecutive pairs of characters?
576
92c2ed05 577To turn C<"abbcccd"> into C<"abccd">:
68dc0745 578
d92eb7b0
GS
579 s/(.)\1/$1/g; # add /s to include newlines
580
581Here's a solution that turns "abbcccd" to "abcd":
582
583 y///cs; # y == tr, but shorter :-)
68dc0745 584
585=head2 How do I expand function calls in a string?
586
587This is documented in L<perlref>. In general, this is fraught with
588quoting and readability problems, but it is possible. To interpolate
5a964f20 589a subroutine call (in list context) into a string:
68dc0745 590
591 print "My sub returned @{[mysub(1,2,3)]} that time.\n";
592
92c2ed05
GS
593See also ``How can I expand variables in text strings?'' in this
594section of the FAQ.
46fc3d4c 595
68dc0745 596=head2 How do I find matching/nesting anything?
597
92c2ed05
GS
598This isn't something that can be done in one regular expression, no
599matter how complicated. To find something between two single
600characters, a pattern like C</x([^x]*)x/> will get the intervening
601bits in $1. For multiple ones, then something more like
602C</alpha(.*?)omega/> would be needed. But none of these deals with
f0f835c2
A
603nested patterns. For balanced expressions using C<(>, C<{>, C<[>
604or C<< < >> as delimiters, use the CPAN module Regexp::Common, or see
605L<perlre/(??{ code })>. For other cases, you'll have to write a parser.
92c2ed05
GS
606
607If you are serious about writing a parser, there are a number of
6a2af475
GS
608modules or oddities that will make your life a lot easier. There are
609the CPAN modules Parse::RecDescent, Parse::Yapp, and Text::Balanced;
83df6a1d
JH
610and the byacc program. Starting from perl 5.8 the Text::Balanced
611is part of the standard distribution.
68dc0745 612
92c2ed05
GS
613One simple destructive, inside-out approach that you might try is to
614pull out the smallest nesting parts one at a time:
5a964f20 615
d92eb7b0 616 while (s/BEGIN((?:(?!BEGIN)(?!END).)*)END//gs) {
5a964f20 617 # do something with $1
197aec24 618 }
5a964f20 619
65acb1b1
TC
620A more complicated and sneaky approach is to make Perl's regular
621expression engine do it for you. This is courtesy Dean Inada, and
622rather has the nature of an Obfuscated Perl Contest entry, but it
623really does work:
624
625 # $_ contains the string to parse
626 # BEGIN and END are the opening and closing markers for the
627 # nested text.
c47ff5f1 628
65acb1b1
TC
629 @( = ('(','');
630 @) = (')','');
631 ($re=$_)=~s/((BEGIN)|(END)|.)/$)[!$3]\Q$1\E$([!$2]/gs;
5ed30e05 632 @$ = (eval{/$re/},$@!~/unmatched/i);
65acb1b1
TC
633 print join("\n",@$[0..$#$]) if( $$[-1] );
634
68dc0745 635=head2 How do I reverse a string?
636
5a964f20 637Use reverse() in scalar context, as documented in
68dc0745 638L<perlfunc/reverse>.
639
640 $reversed = reverse $string;
641
642=head2 How do I expand tabs in a string?
643
5a964f20 644You can do it yourself:
68dc0745 645
646 1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
647
87275199 648Or you can just use the Text::Tabs module (part of the standard Perl
68dc0745 649distribution).
650
651 use Text::Tabs;
652 @expanded_lines = expand(@lines_with_tabs);
653
654=head2 How do I reformat a paragraph?
655
87275199 656Use Text::Wrap (part of the standard Perl distribution):
68dc0745 657
658 use Text::Wrap;
659 print wrap("\t", ' ', @paragraphs);
660
92c2ed05 661The paragraphs you give to Text::Wrap should not contain embedded
46fc3d4c 662newlines. Text::Wrap doesn't justify the lines (flush-right).
663
bc06af74
JH
664Or use the CPAN module Text::Autoformat. Formatting files can be easily
665done by making a shell alias, like so:
666
667 alias fmt="perl -i -MText::Autoformat -n0777 \
668 -e 'print autoformat $_, {all=>1}' $*"
669
670See the documentation for Text::Autoformat to appreciate its many
671capabilities.
672
49d635f9 673=head2 How can I access or change N characters of a string?
68dc0745 674
49d635f9
RGS
675You can access the first characters of a string with substr().
676To get the first character, for example, start at position 0
197aec24 677and grab the string of length 1.
68dc0745 678
68dc0745 679
49d635f9
RGS
680 $string = "Just another Perl Hacker";
681 $first_char = substr( $string, 0, 1 ); # 'J'
68dc0745 682
49d635f9
RGS
683To change part of a string, you can use the optional fourth
684argument which is the replacement string.
68dc0745 685
49d635f9 686 substr( $string, 13, 4, "Perl 5.8.0" );
197aec24 687
49d635f9 688You can also use substr() as an lvalue.
68dc0745 689
49d635f9 690 substr( $string, 13, 4 ) = "Perl 5.8.0";
197aec24 691
68dc0745 692=head2 How do I change the Nth occurrence of something?
693
92c2ed05
GS
694You have to keep track of N yourself. For example, let's say you want
695to change the fifth occurrence of C<"whoever"> or C<"whomever"> into
d92eb7b0
GS
696C<"whosoever"> or C<"whomsoever">, case insensitively. These
697all assume that $_ contains the string to be altered.
68dc0745 698
699 $count = 0;
700 s{((whom?)ever)}{
701 ++$count == 5 # is it the 5th?
702 ? "${2}soever" # yes, swap
703 : $1 # renege and leave it there
d92eb7b0 704 }ige;
68dc0745 705
5a964f20
TC
706In the more general case, you can use the C</g> modifier in a C<while>
707loop, keeping count of matches.
708
709 $WANT = 3;
710 $count = 0;
d92eb7b0 711 $_ = "One fish two fish red fish blue fish";
5a964f20
TC
712 while (/(\w+)\s+fish\b/gi) {
713 if (++$count == $WANT) {
714 print "The third fish is a $1 one.\n";
5a964f20
TC
715 }
716 }
717
92c2ed05 718That prints out: C<"The third fish is a red one."> You can also use a
5a964f20
TC
719repetition count and repeated pattern like this:
720
721 /(?:\w+\s+fish\s+){2}(\w+)\s+fish/i;
722
68dc0745 723=head2 How can I count the number of occurrences of a substring within a string?
724
a6dd486b 725There are a number of ways, with varying efficiency. If you want a
68dc0745 726count of a certain single character (X) within a string, you can use the
727C<tr///> function like so:
728
368c9434 729 $string = "ThisXlineXhasXsomeXx'sXinXit";
68dc0745 730 $count = ($string =~ tr/X//);
d92eb7b0 731 print "There are $count X characters in the string";
68dc0745 732
733This is fine if you are just looking for a single character. However,
734if you are trying to count multiple character substrings within a
735larger string, C<tr///> won't work. What you can do is wrap a while()
736loop around a global pattern match. For example, let's count negative
737integers:
738
739 $string = "-9 55 48 -2 23 -76 4 14 -44";
740 while ($string =~ /-\d+/g) { $count++ }
741 print "There are $count negative numbers in the string";
742
881bdbd4
JH
743Another version uses a global match in list context, then assigns the
744result to a scalar, producing a count of the number of matches.
745
746 $count = () = $string =~ /-\d+/g;
747
68dc0745 748=head2 How do I capitalize all the words on one line?
749
750To make the first letter of each word upper case:
3fe9a6f1 751
68dc0745 752 $line =~ s/\b(\w)/\U$1/g;
753
46fc3d4c 754This has the strange effect of turning "C<don't do it>" into "C<Don'T
a6dd486b 755Do It>". Sometimes you might want this. Other times you might need a
24f1ba9b 756more thorough solution (Suggested by brian d foy):
46fc3d4c 757
758 $string =~ s/ (
759 (^\w) #at the beginning of the line
760 | # or
761 (\s\w) #preceded by whitespace
762 )
763 /\U$1/xg;
764 $string =~ /([\w']+)/\u\L$1/g;
765
68dc0745 766To make the whole line upper case:
3fe9a6f1 767
68dc0745 768 $line = uc($line);
769
770To force each word to be lower case, with the first letter upper case:
3fe9a6f1 771
68dc0745 772 $line =~ s/(\w+)/\u\L$1/g;
773
5a964f20
TC
774You can (and probably should) enable locale awareness of those
775characters by placing a C<use locale> pragma in your program.
92c2ed05 776See L<perllocale> for endless details on locales.
5a964f20 777
65acb1b1 778This is sometimes referred to as putting something into "title
d92eb7b0 779case", but that's not quite accurate. Consider the proper
65acb1b1
TC
780capitalization of the movie I<Dr. Strangelove or: How I Learned to
781Stop Worrying and Love the Bomb>, for example.
782
369b44b4
RGS
783Damian Conway's L<Text::Autoformat> module provides some smart
784case transformations:
785
786 use Text::Autoformat;
787 my $x = "Dr. Strangelove or: How I Learned to Stop ".
788 "Worrying and Love the Bomb";
789
790 print $x, "\n";
791 for my $style (qw( sentence title highlight ))
792 {
793 print autoformat($x, { case => $style }), "\n";
794 }
795
49d635f9 796=head2 How can I split a [character] delimited string except when inside [character]?
68dc0745 797
49d635f9
RGS
798Several modules can handle this sort of pasing---Text::Balanced,
799Text::CVS, Text::CVS_XS, and Text::ParseWords, among others.
800
801Take the example case of trying to split a string that is
802comma-separated into its different fields. You can't use C<split(/,/)>
803because you shouldn't split if the comma is inside quotes. For
804example, take a data line like this:
68dc0745 805
806 SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"
807
808Due to the restriction of the quotes, this is a fairly complex
197aec24 809problem. Thankfully, we have Jeffrey Friedl, author of
49d635f9 810I<Mastering Regular Expressions>, to handle these for us. He
68dc0745 811suggests (assuming your string is contained in $text):
812
813 @new = ();
814 push(@new, $+) while $text =~ m{
815 "([^\"\\]*(?:\\.[^\"\\]*)*)",? # groups the phrase inside the quotes
816 | ([^,]+),?
817 | ,
818 }gx;
819 push(@new, undef) if substr($text,-1,1) eq ',';
820
46fc3d4c 821If you want to represent quotation marks inside a
822quotation-mark-delimited field, escape them with backslashes (eg,
49d635f9 823C<"like \"this\"">.
46fc3d4c 824
87275199 825Alternatively, the Text::ParseWords module (part of the standard Perl
68dc0745 826distribution) lets you say:
827
828 use Text::ParseWords;
829 @new = quotewords(",", 0, $text);
830
a6dd486b 831There's also a Text::CSV (Comma-Separated Values) module on CPAN.
65acb1b1 832
68dc0745 833=head2 How do I strip blank space from the beginning/end of a string?
834
a6dd486b 835Although the simplest approach would seem to be
68dc0745 836
837 $string =~ s/^\s*(.*?)\s*$/$1/;
838
a6dd486b 839not only is this unnecessarily slow and destructive, it also fails with
d92eb7b0 840embedded newlines. It is much faster to do this operation in two steps:
68dc0745 841
842 $string =~ s/^\s+//;
843 $string =~ s/\s+$//;
844
845Or more nicely written as:
846
847 for ($string) {
848 s/^\s+//;
849 s/\s+$//;
850 }
851
5e3006a4 852This idiom takes advantage of the C<foreach> loop's aliasing
5a964f20 853behavior to factor out common code. You can do this
197aec24 854on several strings at once, or arrays, or even the
d92eb7b0 855values of a hash if you use a slice:
5a964f20 856
197aec24 857 # trim whitespace in the scalar, the array,
5a964f20
TC
858 # and all the values in the hash
859 foreach ($scalar, @array, @hash{keys %hash}) {
860 s/^\s+//;
861 s/\s+$//;
862 }
863
65acb1b1
TC
864=head2 How do I pad a string with blanks or pad a number with zeroes?
865
65acb1b1 866In the following examples, C<$pad_len> is the length to which you wish
d92eb7b0
GS
867to pad the string, C<$text> or C<$num> contains the string to be padded,
868and C<$pad_char> contains the padding character. You can use a single
869character string constant instead of the C<$pad_char> variable if you
870know what it is in advance. And in the same way you can use an integer in
871place of C<$pad_len> if you know the pad length in advance.
65acb1b1 872
d92eb7b0
GS
873The simplest method uses the C<sprintf> function. It can pad on the left
874or right with blanks and on the left with zeroes and it will not
875truncate the result. The C<pack> function can only pad strings on the
876right with blanks and it will truncate the result to a maximum length of
877C<$pad_len>.
65acb1b1 878
d92eb7b0 879 # Left padding a string with blanks (no truncation):
04d666b1
RGS
880 $padded = sprintf("%${pad_len}s", $text);
881 $padded = sprintf("%*s", $pad_len, $text); # same thing
65acb1b1 882
d92eb7b0 883 # Right padding a string with blanks (no truncation):
04d666b1
RGS
884 $padded = sprintf("%-${pad_len}s", $text);
885 $padded = sprintf("%-*s", $pad_len, $text); # same thing
65acb1b1 886
197aec24 887 # Left padding a number with 0 (no truncation):
04d666b1
RGS
888 $padded = sprintf("%0${pad_len}d", $num);
889 $padded = sprintf("%0*d", $pad_len, $num); # same thing
65acb1b1 890
d92eb7b0
GS
891 # Right padding a string with blanks using pack (will truncate):
892 $padded = pack("A$pad_len",$text);
65acb1b1 893
d92eb7b0
GS
894If you need to pad with a character other than blank or zero you can use
895one of the following methods. They all generate a pad string with the
896C<x> operator and combine that with C<$text>. These methods do
897not truncate C<$text>.
65acb1b1 898
d92eb7b0 899Left and right padding with any character, creating a new string:
65acb1b1 900
d92eb7b0
GS
901 $padded = $pad_char x ( $pad_len - length( $text ) ) . $text;
902 $padded = $text . $pad_char x ( $pad_len - length( $text ) );
65acb1b1 903
d92eb7b0 904Left and right padding with any character, modifying C<$text> directly:
65acb1b1 905
d92eb7b0
GS
906 substr( $text, 0, 0 ) = $pad_char x ( $pad_len - length( $text ) );
907 $text .= $pad_char x ( $pad_len - length( $text ) );
65acb1b1 908
68dc0745 909=head2 How do I extract selected columns from a string?
910
911Use substr() or unpack(), both documented in L<perlfunc>.
197aec24 912If you prefer thinking in terms of columns instead of widths,
5a964f20
TC
913you can use this kind of thing:
914
915 # determine the unpack format needed to split Linux ps output
916 # arguments are cut columns
917 my $fmt = cut2fmt(8, 14, 20, 26, 30, 34, 41, 47, 59, 63, 67, 72);
918
197aec24 919 sub cut2fmt {
5a964f20
TC
920 my(@positions) = @_;
921 my $template = '';
922 my $lastpos = 1;
923 for my $place (@positions) {
197aec24 924 $template .= "A" . ($place - $lastpos) . " ";
5a964f20
TC
925 $lastpos = $place;
926 }
927 $template .= "A*";
928 return $template;
929 }
68dc0745 930
931=head2 How do I find the soundex value of a string?
932
87275199 933Use the standard Text::Soundex module distributed with Perl.
a6dd486b 934Before you do so, you may want to determine whether `soundex' is in
d92eb7b0
GS
935fact what you think it is. Knuth's soundex algorithm compresses words
936into a small space, and so it does not necessarily distinguish between
937two words which you might want to appear separately. For example, the
938last names `Knuth' and `Kant' are both mapped to the soundex code K530.
939If Text::Soundex does not do what you are looking for, you might want
940to consider the String::Approx module available at CPAN.
68dc0745 941
942=head2 How can I expand variables in text strings?
943
944Let's assume that you have a string like:
945
946 $text = 'this has a $foo in it and a $bar';
5a964f20
TC
947
948If those were both global variables, then this would
949suffice:
950
65acb1b1 951 $text =~ s/\$(\w+)/${$1}/g; # no /e needed
68dc0745 952
5a964f20
TC
953But since they are probably lexicals, or at least, they could
954be, you'd have to do this:
68dc0745 955
956 $text =~ s/(\$\w+)/$1/eeg;
65acb1b1 957 die if $@; # needed /ee, not /e
68dc0745 958
5a964f20
TC
959It's probably better in the general case to treat those
960variables as entries in some special hash. For example:
961
197aec24 962 %user_defs = (
5a964f20
TC
963 foo => 23,
964 bar => 19,
965 );
966 $text =~ s/\$(\w+)/$user_defs{$1}/g;
68dc0745 967
92c2ed05 968See also ``How do I expand function calls in a string?'' in this section
46fc3d4c 969of the FAQ.
970
68dc0745 971=head2 What's wrong with always quoting "$vars"?
972
a6dd486b
JB
973The problem is that those double-quotes force stringification--
974coercing numbers and references into strings--even when you
975don't want them to be strings. Think of it this way: double-quote
197aec24 976expansion is used to produce new strings. If you already
65acb1b1 977have a string, why do you need more?
68dc0745 978
979If you get used to writing odd things like these:
980
981 print "$var"; # BAD
982 $new = "$old"; # BAD
983 somefunc("$var"); # BAD
984
985You'll be in trouble. Those should (in 99.8% of the cases) be
986the simpler and more direct:
987
988 print $var;
989 $new = $old;
990 somefunc($var);
991
992Otherwise, besides slowing you down, you're going to break code when
993the thing in the scalar is actually neither a string nor a number, but
994a reference:
995
996 func(\@array);
997 sub func {
998 my $aref = shift;
999 my $oref = "$aref"; # WRONG
1000 }
1001
1002You can also get into subtle problems on those few operations in Perl
1003that actually do care about the difference between a string and a
1004number, such as the magical C<++> autoincrement operator or the
1005syscall() function.
1006
197aec24 1007Stringification also destroys arrays.
5a964f20
TC
1008
1009 @lines = `command`;
1010 print "@lines"; # WRONG - extra blanks
1011 print @lines; # right
1012
04d666b1 1013=head2 Why don't my E<lt>E<lt>HERE documents work?
68dc0745 1014
1015Check for these three things:
1016
1017=over 4
1018
04d666b1 1019=item There must be no space after the E<lt>E<lt> part.
68dc0745 1020
197aec24 1021=item There (probably) should be a semicolon at the end.
68dc0745 1022
197aec24 1023=item You can't (easily) have any space in front of the tag.
68dc0745 1024
1025=back
1026
197aec24 1027If you want to indent the text in the here document, you
5a964f20
TC
1028can do this:
1029
1030 # all in one
1031 ($VAR = <<HERE_TARGET) =~ s/^\s+//gm;
1032 your text
1033 goes here
1034 HERE_TARGET
1035
1036But the HERE_TARGET must still be flush against the margin.
197aec24 1037If you want that indented also, you'll have to quote
5a964f20
TC
1038in the indentation.
1039
1040 ($quote = <<' FINIS') =~ s/^\s+//gm;
1041 ...we will have peace, when you and all your works have
1042 perished--and the works of your dark master to whom you
1043 would deliver us. You are a liar, Saruman, and a corrupter
1044 of men's hearts. --Theoden in /usr/src/perl/taint.c
1045 FINIS
83ded9ee 1046 $quote =~ s/\s+--/\n--/;
5a964f20
TC
1047
1048A nice general-purpose fixer-upper function for indented here documents
1049follows. It expects to be called with a here document as its argument.
1050It looks to see whether each line begins with a common substring, and
a6dd486b
JB
1051if so, strips that substring off. Otherwise, it takes the amount of leading
1052whitespace found on the first line and removes that much off each
5a964f20
TC
1053subsequent line.
1054
1055 sub fix {
1056 local $_ = shift;
a6dd486b 1057 my ($white, $leader); # common whitespace and common leading string
5a964f20
TC
1058 if (/^\s*(?:([^\w\s]+)(\s*).*\n)(?:\s*\1\2?.*\n)+$/) {
1059 ($white, $leader) = ($2, quotemeta($1));
1060 } else {
1061 ($white, $leader) = (/^(\s+)/, '');
1062 }
1063 s/^\s*?$leader(?:$white)?//gm;
1064 return $_;
1065 }
1066
c8db1d39 1067This works with leading special strings, dynamically determined:
5a964f20
TC
1068
1069 $remember_the_main = fix<<' MAIN_INTERPRETER_LOOP';
1070 @@@ int
1071 @@@ runops() {
1072 @@@ SAVEI32(runlevel);
1073 @@@ runlevel++;
d92eb7b0 1074 @@@ while ( op = (*op->op_ppaddr)() );
5a964f20
TC
1075 @@@ TAINT_NOT;
1076 @@@ return 0;
1077 @@@ }
1078 MAIN_INTERPRETER_LOOP
1079
a6dd486b 1080Or with a fixed amount of leading whitespace, with remaining
5a964f20
TC
1081indentation correctly preserved:
1082
1083 $poem = fix<<EVER_ON_AND_ON;
1084 Now far ahead the Road has gone,
1085 And I must follow, if I can,
1086 Pursuing it with eager feet,
1087 Until it joins some larger way
1088 Where many paths and errands meet.
1089 And whither then? I cannot say.
1090 --Bilbo in /usr/src/perl/pp_ctl.c
1091 EVER_ON_AND_ON
1092
68dc0745 1093=head1 Data: Arrays
1094
65acb1b1
TC
1095=head2 What is the difference between a list and an array?
1096
1097An array has a changeable length. A list does not. An array is something
1098you can push or pop, while a list is a set of values. Some people make
1099the distinction that a list is a value while an array is a variable.
1100Subroutines are passed and return lists, you put things into list
1101context, you initialize arrays with lists, and you foreach() across
1102a list. C<@> variables are arrays, anonymous arrays are arrays, arrays
1103in scalar context behave like the number of elements in them, subroutines
a6dd486b 1104access their arguments through the array C<@_>, and push/pop/shift only work
65acb1b1
TC
1105on arrays.
1106
1107As a side note, there's no such thing as a list in scalar context.
1108When you say
1109
1110 $scalar = (2, 5, 7, 9);
1111
d92eb7b0
GS
1112you're using the comma operator in scalar context, so it uses the scalar
1113comma operator. There never was a list there at all! This causes the
1114last value to be returned: 9.
65acb1b1 1115
68dc0745 1116=head2 What is the difference between $array[1] and @array[1]?
1117
a6dd486b 1118The former is a scalar value; the latter an array slice, making
68dc0745 1119it a list with one (scalar) value. You should use $ when you want a
1120scalar value (most of the time) and @ when you want a list with one
1121scalar value in it (very, very rarely; nearly never, in fact).
1122
1123Sometimes it doesn't make a difference, but sometimes it does.
1124For example, compare:
1125
1126 $good[0] = `some program that outputs several lines`;
1127
1128with
1129
1130 @bad[0] = `same program that outputs several lines`;
1131
197aec24 1132The C<use warnings> pragma and the B<-w> flag will warn you about these
9f1b1f2d 1133matters.
68dc0745 1134
d92eb7b0 1135=head2 How can I remove duplicate elements from a list or array?
68dc0745 1136
1137There are several possible ways, depending on whether the array is
1138ordered and whether you wish to preserve the ordering.
1139
1140=over 4
1141
551e1d92
RB
1142=item a)
1143
1144If @in is sorted, and you want @out to be sorted:
5a964f20 1145(this assumes all true values in the array)
68dc0745 1146
a4341a65 1147 $prev = "not equal to $in[0]";
3bc5ef3e 1148 @out = grep($_ ne $prev && ($prev = $_, 1), @in);
68dc0745 1149
c8db1d39 1150This is nice in that it doesn't use much extra memory, simulating
3bc5ef3e
HG
1151uniq(1)'s behavior of removing only adjacent duplicates. The ", 1"
1152guarantees that the expression is true (so that grep picks it up)
1153even if the $_ is 0, "", or undef.
68dc0745 1154
551e1d92
RB
1155=item b)
1156
1157If you don't know whether @in is sorted:
68dc0745 1158
1159 undef %saw;
1160 @out = grep(!$saw{$_}++, @in);
1161
551e1d92
RB
1162=item c)
1163
1164Like (b), but @in contains only small integers:
68dc0745 1165
1166 @out = grep(!$saw[$_]++, @in);
1167
551e1d92
RB
1168=item d)
1169
1170A way to do (b) without any loops or greps:
68dc0745 1171
1172 undef %saw;
1173 @saw{@in} = ();
1174 @out = sort keys %saw; # remove sort if undesired
1175
551e1d92
RB
1176=item e)
1177
1178Like (d), but @in contains only small positive integers:
68dc0745 1179
1180 undef @ary;
1181 @ary[@in] = @in;
87275199 1182 @out = grep {defined} @ary;
68dc0745 1183
1184=back
1185
65acb1b1
TC
1186But perhaps you should have been using a hash all along, eh?
1187
ddbc1f16 1188=head2 How can I tell whether a certain element is contained in a list or array?
5a964f20
TC
1189
1190Hearing the word "in" is an I<in>dication that you probably should have
1191used a hash, not a list or array, to store your data. Hashes are
1192designed to answer this question quickly and efficiently. Arrays aren't.
68dc0745 1193
5a964f20
TC
1194That being said, there are several ways to approach this. If you
1195are going to make this query many times over arbitrary string values,
881bdbd4
JH
1196the fastest way is probably to invert the original array and maintain a
1197hash whose keys are the first array's values.
68dc0745 1198
1199 @blues = qw/azure cerulean teal turquoise lapis-lazuli/;
881bdbd4 1200 %is_blue = ();
68dc0745 1201 for (@blues) { $is_blue{$_} = 1 }
1202
1203Now you can check whether $is_blue{$some_color}. It might have been a
1204good idea to keep the blues all in a hash in the first place.
1205
1206If the values are all small integers, you could use a simple indexed
1207array. This kind of an array will take up less space:
1208
1209 @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
881bdbd4 1210 @is_tiny_prime = ();
d92eb7b0
GS
1211 for (@primes) { $is_tiny_prime[$_] = 1 }
1212 # or simply @istiny_prime[@primes] = (1) x @primes;
68dc0745 1213
1214Now you check whether $is_tiny_prime[$some_number].
1215
1216If the values in question are integers instead of strings, you can save
1217quite a lot of space by using bit strings instead:
1218
1219 @articles = ( 1..10, 150..2000, 2017 );
1220 undef $read;
7b8d334a 1221 for (@articles) { vec($read,$_,1) = 1 }
68dc0745 1222
1223Now check whether C<vec($read,$n,1)> is true for some C<$n>.
1224
1225Please do not use
1226
a6dd486b 1227 ($is_there) = grep $_ eq $whatever, @array;
68dc0745 1228
1229or worse yet
1230
a6dd486b 1231 ($is_there) = grep /$whatever/, @array;
68dc0745 1232
1233These are slow (checks every element even if the first matches),
1234inefficient (same reason), and potentially buggy (what if there are
d92eb7b0 1235regex characters in $whatever?). If you're only testing once, then
65acb1b1
TC
1236use:
1237
1238 $is_there = 0;
1239 foreach $elt (@array) {
1240 if ($elt eq $elt_to_find) {
1241 $is_there = 1;
1242 last;
1243 }
1244 }
1245 if ($is_there) { ... }
68dc0745 1246
1247=head2 How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
1248
1249Use a hash. Here's code to do both and more. It assumes that
1250each element is unique in a given array:
1251
1252 @union = @intersection = @difference = ();
1253 %count = ();
1254 foreach $element (@array1, @array2) { $count{$element}++ }
1255 foreach $element (keys %count) {
1256 push @union, $element;
1257 push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
1258 }
1259
d92eb7b0 1260Note that this is the I<symmetric difference>, that is, all elements in
a6dd486b 1261either A or in B but not in both. Think of it as an xor operation.
d92eb7b0 1262
65acb1b1
TC
1263=head2 How do I test whether two arrays or hashes are equal?
1264
1265The following code works for single-level arrays. It uses a stringwise
1266comparison, and does not distinguish defined versus undefined empty
1267strings. Modify if you have other needs.
1268
1269 $are_equal = compare_arrays(\@frogs, \@toads);
1270
1271 sub compare_arrays {
1272 my ($first, $second) = @_;
9f1b1f2d 1273 no warnings; # silence spurious -w undef complaints
65acb1b1
TC
1274 return 0 unless @$first == @$second;
1275 for (my $i = 0; $i < @$first; $i++) {
1276 return 0 if $first->[$i] ne $second->[$i];
1277 }
1278 return 1;
1279 }
1280
1281For multilevel structures, you may wish to use an approach more
1282like this one. It uses the CPAN module FreezeThaw:
1283
1284 use FreezeThaw qw(cmpStr);
1285 @a = @b = ( "this", "that", [ "more", "stuff" ] );
1286
1287 printf "a and b contain %s arrays\n",
197aec24
RGS
1288 cmpStr(\@a, \@b) == 0
1289 ? "the same"
65acb1b1
TC
1290 : "different";
1291
1292This approach also works for comparing hashes. Here
1293we'll demonstrate two different answers:
1294
1295 use FreezeThaw qw(cmpStr cmpStrHard);
1296
1297 %a = %b = ( "this" => "that", "extra" => [ "more", "stuff" ] );
1298 $a{EXTRA} = \%b;
197aec24 1299 $b{EXTRA} = \%a;
65acb1b1
TC
1300
1301 printf "a and b contain %s hashes\n",
1302 cmpStr(\%a, \%b) == 0 ? "the same" : "different";
1303
1304 printf "a and b contain %s hashes\n",
1305 cmpStrHard(\%a, \%b) == 0 ? "the same" : "different";
1306
1307
1308The first reports that both those the hashes contain the same data,
1309while the second reports that they do not. Which you prefer is left as
1310an exercise to the reader.
1311
68dc0745 1312=head2 How do I find the first array element for which a condition is true?
1313
49d635f9
RGS
1314To find the first array element which satisfies a condition, you can
1315use the first() function in the List::Util module, which comes with
1316Perl 5.8. This example finds the first element that contains "Perl".
1317
1318 use List::Util qw(first);
197aec24 1319
49d635f9 1320 my $element = first { /Perl/ } @array;
197aec24 1321
49d635f9
RGS
1322If you cannot use List::Util, you can make your own loop to do the
1323same thing. Once you find the element, you stop the loop with last.
1324
1325 my $found;
1326 foreach my $element ( @array )
1327 {
1328 if( /Perl/ ) { $found = $element; last }
1329 }
1330
1331If you want the array index, you can iterate through the indices
1332and check the array element at each index until you find one
1333that satisfies the condition.
1334
197aec24
RGS
1335 my( $found, $index ) = ( undef, -1 );
1336 for( $i = 0; $i < @array; $i++ )
49d635f9 1337 {
197aec24
RGS
1338 if( $array[$i] =~ /Perl/ )
1339 {
49d635f9 1340 $found = $array[$i];
197aec24 1341 $index = $i;
49d635f9
RGS
1342 last;
1343 }
68dc0745 1344 }
68dc0745 1345
1346=head2 How do I handle linked lists?
1347
1348In general, you usually don't need a linked list in Perl, since with
1349regular arrays, you can push and pop or shift and unshift at either end,
5a964f20 1350or you can use splice to add and/or remove arbitrary number of elements at
87275199 1351arbitrary points. Both pop and shift are both O(1) operations on Perl's
5a964f20
TC
1352dynamic arrays. In the absence of shifts and pops, push in general
1353needs to reallocate on the order every log(N) times, and unshift will
1354need to copy pointers each time.
68dc0745 1355
1356If you really, really wanted, you could use structures as described in
1357L<perldsc> or L<perltoot> and do just what the algorithm book tells you
65acb1b1
TC
1358to do. For example, imagine a list node like this:
1359
1360 $node = {
1361 VALUE => 42,
1362 LINK => undef,
1363 };
1364
1365You could walk the list this way:
1366
1367 print "List: ";
1368 for ($node = $head; $node; $node = $node->{LINK}) {
1369 print $node->{VALUE}, " ";
1370 }
1371 print "\n";
1372
a6dd486b 1373You could add to the list this way:
65acb1b1
TC
1374
1375 my ($head, $tail);
1376 $tail = append($head, 1); # grow a new head
1377 for $value ( 2 .. 10 ) {
1378 $tail = append($tail, $value);
1379 }
1380
1381 sub append {
1382 my($list, $value) = @_;
1383 my $node = { VALUE => $value };
1384 if ($list) {
1385 $node->{LINK} = $list->{LINK};
1386 $list->{LINK} = $node;
1387 } else {
1388 $_[0] = $node; # replace caller's version
1389 }
1390 return $node;
1391 }
1392
1393But again, Perl's built-in are virtually always good enough.
68dc0745 1394
1395=head2 How do I handle circular lists?
1396
1397Circular lists could be handled in the traditional fashion with linked
1398lists, or you could just do something like this with an array:
1399
1400 unshift(@array, pop(@array)); # the last shall be first
1401 push(@array, shift(@array)); # and vice versa
1402
1403=head2 How do I shuffle an array randomly?
1404
45bbf655
JH
1405If you either have Perl 5.8.0 or later installed, or if you have
1406Scalar-List-Utils 1.03 or later installed, you can say:
1407
f05bbc40 1408 use List::Util 'shuffle';
45bbf655
JH
1409
1410 @shuffled = shuffle(@list);
1411
f05bbc40 1412If not, you can use a Fisher-Yates shuffle.
5a964f20 1413
5a964f20 1414 sub fisher_yates_shuffle {
cc30d1a7
JH
1415 my $deck = shift; # $deck is a reference to an array
1416 my $i = @$deck;
f05bbc40 1417 while ($i--) {
5a964f20 1418 my $j = int rand ($i+1);
cc30d1a7 1419 @$deck[$i,$j] = @$deck[$j,$i];
5a964f20
TC
1420 }
1421 }
1422
cc30d1a7
JH
1423 # shuffle my mpeg collection
1424 #
1425 my @mpeg = <audio/*/*.mp3>;
1426 fisher_yates_shuffle( \@mpeg ); # randomize @mpeg in place
1427 print @mpeg;
5a964f20 1428
45bbf655
JH
1429Note that the above implementation shuffles an array in place,
1430unlike the List::Util::shuffle() which takes a list and returns
1431a new shuffled list.
1432
d92eb7b0 1433You've probably seen shuffling algorithms that work using splice,
a6dd486b 1434randomly picking another element to swap the current element with
68dc0745 1435
1436 srand;
1437 @new = ();
1438 @old = 1 .. 10; # just a demo
1439 while (@old) {
1440 push(@new, splice(@old, rand @old, 1));
1441 }
1442
5a964f20
TC
1443This is bad because splice is already O(N), and since you do it N times,
1444you just invented a quadratic algorithm; that is, O(N**2). This does
1445not scale, although Perl is so efficient that you probably won't notice
1446this until you have rather largish arrays.
68dc0745 1447
1448=head2 How do I process/modify each element of an array?
1449
1450Use C<for>/C<foreach>:
1451
1452 for (@lines) {
5a964f20
TC
1453 s/foo/bar/; # change that word
1454 y/XZ/ZX/; # swap those letters
68dc0745 1455 }
1456
1457Here's another; let's compute spherical volumes:
1458
5a964f20 1459 for (@volumes = @radii) { # @volumes has changed parts
68dc0745 1460 $_ **= 3;
1461 $_ *= (4/3) * 3.14159; # this will be constant folded
1462 }
197aec24 1463
49d635f9
RGS
1464which can also be done with map() which is made to transform
1465one list into another:
1466
1467 @volumes = map {$_ ** 3 * (4/3) * 3.14159} @radii;
68dc0745 1468
76817d6d
JH
1469If you want to do the same thing to modify the values of the
1470hash, you can use the C<values> function. As of Perl 5.6
1471the values are not copied, so if you modify $orbit (in this
1472case), you modify the value.
5a964f20 1473
76817d6d 1474 for $orbit ( values %orbits ) {
197aec24 1475 ($orbit **= 3) *= (4/3) * 3.14159;
5a964f20 1476 }
818c4caa 1477
76817d6d
JH
1478Prior to perl 5.6 C<values> returned copies of the values,
1479so older perl code often contains constructions such as
1480C<@orbits{keys %orbits}> instead of C<values %orbits> where
1481the hash is to be modified.
818c4caa 1482
68dc0745 1483=head2 How do I select a random element from an array?
1484
1485Use the rand() function (see L<perlfunc/rand>):
1486
5a964f20 1487 # at the top of the program:
68dc0745 1488 srand; # not needed for 5.004 and later
5a964f20
TC
1489
1490 # then later on
68dc0745 1491 $index = rand @array;
1492 $element = $array[$index];
1493
5a964f20 1494Make sure you I<only call srand once per program, if then>.
197aec24 1495If you are calling it more than once (such as before each
5a964f20
TC
1496call to rand), you're almost certainly doing something wrong.
1497
68dc0745 1498=head2 How do I permute N elements of a list?
1499
49d635f9
RGS
1500Use the List::Permutor module on CPAN. If the list is
1501actually an array, try the Algorithm::Permute module (also
1502on CPAN). It's written in XS code and is very efficient.
1503
1504 use Algorithm::Permute;
1505 my @array = 'a'..'d';
1506 my $p_iterator = Algorithm::Permute->new ( \@array );
1507 while (my @perm = $p_iterator->next) {
1508 print "next permutation: (@perm)\n";
1509 }
1510
197aec24
RGS
1511For even faster execution, you could do:
1512
1513 use Algorithm::Permute;
1514 my @array = 'a'..'d';
1515 Algorithm::Permute::permute {
1516 print "next permutation: (@array)\n";
1517 } @array;
1518
49d635f9
RGS
1519Here's a little program that generates all permutations of
1520all the words on each line of input. The algorithm embodied
1521in the permute() function is discussed in Volume 4 (still
1522unpublished) of Knuth's I<The Art of Computer Programming>
1523and will work on any list:
1524
1525 #!/usr/bin/perl -n
1526 # Fischer-Kause ordered permutation generator
1527
1528 sub permute (&@) {
1529 my $code = shift;
1530 my @idx = 0..$#_;
1531 while ( $code->(@_[@idx]) ) {
1532 my $p = $#idx;
1533 --$p while $idx[$p-1] > $idx[$p];
1534 my $q = $p or return;
1535 push @idx, reverse splice @idx, $p;
1536 ++$q while $idx[$p-1] > $idx[$q];
1537 @idx[$p-1,$q]=@idx[$q,$p-1];
1538 }
68dc0745 1539 }
68dc0745 1540
49d635f9 1541 permute {print"@_\n"} split;
b8d2732a 1542
68dc0745 1543=head2 How do I sort an array by (anything)?
1544
1545Supply a comparison function to sort() (described in L<perlfunc/sort>):
1546
1547 @list = sort { $a <=> $b } @list;
1548
1549The default sort function is cmp, string comparison, which would
c47ff5f1 1550sort C<(1, 2, 10)> into C<(1, 10, 2)>. C<< <=> >>, used above, is
68dc0745 1551the numerical comparison operator.
1552
1553If you have a complicated function needed to pull out the part you
1554want to sort on, then don't do it inside the sort function. Pull it
1555out first, because the sort BLOCK can be called many times for the
1556same element. Here's an example of how to pull out the first word
1557after the first number on each item, and then sort those words
1558case-insensitively.
1559
1560 @idx = ();
1561 for (@data) {
1562 ($item) = /\d+\s*(\S+)/;
1563 push @idx, uc($item);
1564 }
1565 @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];
1566
a6dd486b 1567which could also be written this way, using a trick
68dc0745 1568that's come to be known as the Schwartzian Transform:
1569
1570 @sorted = map { $_->[0] }
1571 sort { $a->[1] cmp $b->[1] }
d92eb7b0 1572 map { [ $_, uc( (/\d+\s*(\S+)/)[0]) ] } @data;
68dc0745 1573
1574If you need to sort on several fields, the following paradigm is useful.
1575
1576 @sorted = sort { field1($a) <=> field1($b) ||
1577 field2($a) cmp field2($b) ||
1578 field3($a) cmp field3($b)
1579 } @data;
1580
1581This can be conveniently combined with precalculation of keys as given
1582above.
1583
06a5f41f 1584See the F<sort> artitcle article in the "Far More Than You Ever Wanted
49d635f9 1585To Know" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz for
06a5f41f 1586more about this approach.
68dc0745 1587
1588See also the question below on sorting hashes.
1589
1590=head2 How do I manipulate arrays of bits?
1591
1592Use pack() and unpack(), or else vec() and the bitwise operations.
1593
1594For example, this sets $vec to have bit N set if $ints[N] was set:
1595
1596 $vec = '';
1597 foreach(@ints) { vec($vec,$_,1) = 1 }
1598
cc30d1a7 1599Here's how, given a vector in $vec, you can
68dc0745 1600get those bits into your @ints array:
1601
1602 sub bitvec_to_list {
1603 my $vec = shift;
1604 my @ints;
1605 # Find null-byte density then select best algorithm
1606 if ($vec =~ tr/\0// / length $vec > 0.95) {
1607 use integer;
1608 my $i;
1609 # This method is faster with mostly null-bytes
1610 while($vec =~ /[^\0]/g ) {
1611 $i = -9 + 8 * pos $vec;
1612 push @ints, $i if vec($vec, ++$i, 1);
1613 push @ints, $i if vec($vec, ++$i, 1);
1614 push @ints, $i if vec($vec, ++$i, 1);
1615 push @ints, $i if vec($vec, ++$i, 1);
1616 push @ints, $i if vec($vec, ++$i, 1);
1617 push @ints, $i if vec($vec, ++$i, 1);
1618 push @ints, $i if vec($vec, ++$i, 1);
1619 push @ints, $i if vec($vec, ++$i, 1);
1620 }
1621 } else {
1622 # This method is a fast general algorithm
1623 use integer;
1624 my $bits = unpack "b*", $vec;
1625 push @ints, 0 if $bits =~ s/^(\d)// && $1;
1626 push @ints, pos $bits while($bits =~ /1/g);
1627 }
1628 return \@ints;
1629 }
1630
1631This method gets faster the more sparse the bit vector is.
1632(Courtesy of Tim Bunce and Winfried Koenig.)
1633
76817d6d
JH
1634You can make the while loop a lot shorter with this suggestion
1635from Benjamin Goldberg:
1636
1637 while($vec =~ /[^\0]+/g ) {
1638 push @ints, grep vec($vec, $_, 1), $-[0] * 8 .. $+[0] * 8;
1639 }
1640
cc30d1a7
JH
1641Or use the CPAN module Bit::Vector:
1642
1643 $vector = Bit::Vector->new($num_of_bits);
1644 $vector->Index_List_Store(@ints);
1645 @ints = $vector->Index_List_Read();
1646
1647Bit::Vector provides efficient methods for bit vector, sets of small integers
197aec24 1648and "big int" math.
cc30d1a7
JH
1649
1650Here's a more extensive illustration using vec():
65acb1b1
TC
1651
1652 # vec demo
1653 $vector = "\xff\x0f\xef\xfe";
197aec24 1654 print "Ilya's string \\xff\\x0f\\xef\\xfe represents the number ",
65acb1b1
TC
1655 unpack("N", $vector), "\n";
1656 $is_set = vec($vector, 23, 1);
1657 print "Its 23rd bit is ", $is_set ? "set" : "clear", ".\n";
1658 pvec($vector);
1659
1660 set_vec(1,1,1);
1661 set_vec(3,1,1);
1662 set_vec(23,1,1);
1663
1664 set_vec(3,1,3);
1665 set_vec(3,2,3);
1666 set_vec(3,4,3);
1667 set_vec(3,4,7);
1668 set_vec(3,8,3);
1669 set_vec(3,8,7);
1670
1671 set_vec(0,32,17);
1672 set_vec(1,32,17);
1673
197aec24 1674 sub set_vec {
65acb1b1
TC
1675 my ($offset, $width, $value) = @_;
1676 my $vector = '';
1677 vec($vector, $offset, $width) = $value;
1678 print "offset=$offset width=$width value=$value\n";
1679 pvec($vector);
1680 }
1681
1682 sub pvec {
1683 my $vector = shift;
1684 my $bits = unpack("b*", $vector);
1685 my $i = 0;
1686 my $BASE = 8;
1687
1688 print "vector length in bytes: ", length($vector), "\n";
1689 @bytes = unpack("A8" x length($vector), $bits);
1690 print "bits are: @bytes\n\n";
197aec24 1691 }
65acb1b1 1692
68dc0745 1693=head2 Why does defined() return true on empty arrays and hashes?
1694
65acb1b1
TC
1695The short story is that you should probably only use defined on scalars or
1696functions, not on aggregates (arrays and hashes). See L<perlfunc/defined>
1697in the 5.004 release or later of Perl for more detail.
68dc0745 1698
1699=head1 Data: Hashes (Associative Arrays)
1700
1701=head2 How do I process an entire hash?
1702
1703Use the each() function (see L<perlfunc/each>) if you don't care
1704whether it's sorted:
1705
5a964f20 1706 while ( ($key, $value) = each %hash) {
68dc0745 1707 print "$key = $value\n";
1708 }
1709
1710If you want it sorted, you'll have to use foreach() on the result of
1711sorting the keys as shown in an earlier question.
1712
1713=head2 What happens if I add or remove keys from a hash while iterating over it?
1714
d92eb7b0
GS
1715Don't do that. :-)
1716
1717[lwall] In Perl 4, you were not allowed to modify a hash at all while
87275199 1718iterating over it. In Perl 5 you can delete from it, but you still
d92eb7b0
GS
1719can't add to it, because that might cause a doubling of the hash table,
1720in which half the entries get copied up to the new top half of the
87275199 1721table, at which point you've totally bamboozled the iterator code.
d92eb7b0
GS
1722Even if the table doesn't double, there's no telling whether your new
1723entry will be inserted before or after the current iterator position.
1724
a6dd486b 1725Either treasure up your changes and make them after the iterator finishes
d92eb7b0
GS
1726or use keys to fetch all the old keys at once, and iterate over the list
1727of keys.
68dc0745 1728
1729=head2 How do I look up a hash element by value?
1730
1731Create a reverse hash:
1732
1733 %by_value = reverse %by_key;
1734 $key = $by_value{$value};
1735
1736That's not particularly efficient. It would be more space-efficient
1737to use:
1738
1739 while (($key, $value) = each %by_key) {
1740 $by_value{$value} = $key;
1741 }
1742
d92eb7b0
GS
1743If your hash could have repeated values, the methods above will only find
1744one of the associated keys. This may or may not worry you. If it does
1745worry you, you can always reverse the hash into a hash of arrays instead:
1746
1747 while (($key, $value) = each %by_key) {
1748 push @{$key_list_by_value{$value}}, $key;
1749 }
68dc0745 1750
1751=head2 How can I know how many entries are in a hash?
1752
1753If you mean how many keys, then all you have to do is
875e5c2f 1754use the keys() function in a scalar context:
68dc0745 1755
875e5c2f 1756 $num_keys = keys %hash;
68dc0745 1757
197aec24
RGS
1758The keys() function also resets the iterator, which means that you may
1759see strange results if you use this between uses of other hash operators
875e5c2f 1760such as each().
68dc0745 1761
1762=head2 How do I sort a hash (optionally by value instead of key)?
1763
1764Internally, hashes are stored in a way that prevents you from imposing
1765an order on key-value pairs. Instead, you have to sort a list of the
1766keys or values:
1767
1768 @keys = sort keys %hash; # sorted by key
1769 @keys = sort {
1770 $hash{$a} cmp $hash{$b}
1771 } keys %hash; # and by value
1772
1773Here we'll do a reverse numeric sort by value, and if two keys are
a6dd486b
JB
1774identical, sort by length of key, or if that fails, by straight ASCII
1775comparison of the keys (well, possibly modified by your locale--see
68dc0745 1776L<perllocale>).
1777
1778 @keys = sort {
1779 $hash{$b} <=> $hash{$a}
1780 ||
1781 length($b) <=> length($a)
1782 ||
1783 $a cmp $b
1784 } keys %hash;
1785
1786=head2 How can I always keep my hash sorted?
1787
1788You can look into using the DB_File module and tie() using the
1789$DB_BTREE hash bindings as documented in L<DB_File/"In Memory Databases">.
5a964f20 1790The Tie::IxHash module from CPAN might also be instructive.
68dc0745 1791
1792=head2 What's the difference between "delete" and "undef" with hashes?
1793
92993692
JH
1794Hashes contain pairs of scalars: the first is the key, the
1795second is the value. The key will be coerced to a string,
1796although the value can be any kind of scalar: string,
1797number, or reference. If a key $key is present in
1798%hash, C<exists($hash{$key})> will return true. The value
1799for a given key can be C<undef>, in which case
1800C<$hash{$key}> will be C<undef> while C<exists $hash{$key}>
1801will return true. This corresponds to (C<$key>, C<undef>)
1802being in the hash.
68dc0745 1803
92993692 1804Pictures help... here's the %hash table:
68dc0745 1805
1806 keys values
1807 +------+------+
1808 | a | 3 |
1809 | x | 7 |
1810 | d | 0 |
1811 | e | 2 |
1812 +------+------+
1813
1814And these conditions hold
1815
92993692
JH
1816 $hash{'a'} is true
1817 $hash{'d'} is false
1818 defined $hash{'d'} is true
1819 defined $hash{'a'} is true
1820 exists $hash{'a'} is true (Perl5 only)
1821 grep ($_ eq 'a', keys %hash) is true
68dc0745 1822
1823If you now say
1824
92993692 1825 undef $hash{'a'}
68dc0745 1826
1827your table now reads:
1828
1829
1830 keys values
1831 +------+------+
1832 | a | undef|
1833 | x | 7 |
1834 | d | 0 |
1835 | e | 2 |
1836 +------+------+
1837
1838and these conditions now hold; changes in caps:
1839
92993692
JH
1840 $hash{'a'} is FALSE
1841 $hash{'d'} is false
1842 defined $hash{'d'} is true
1843 defined $hash{'a'} is FALSE
1844 exists $hash{'a'} is true (Perl5 only)
1845 grep ($_ eq 'a', keys %hash) is true
68dc0745 1846
1847Notice the last two: you have an undef value, but a defined key!
1848
1849Now, consider this:
1850
92993692 1851 delete $hash{'a'}
68dc0745 1852
1853your table now reads:
1854
1855 keys values
1856 +------+------+
1857 | x | 7 |
1858 | d | 0 |
1859 | e | 2 |
1860 +------+------+
1861
1862and these conditions now hold; changes in caps:
1863
92993692
JH
1864 $hash{'a'} is false
1865 $hash{'d'} is false
1866 defined $hash{'d'} is true
1867 defined $hash{'a'} is false
1868 exists $hash{'a'} is FALSE (Perl5 only)
1869 grep ($_ eq 'a', keys %hash) is FALSE
68dc0745 1870
1871See, the whole entry is gone!
1872
1873=head2 Why don't my tied hashes make the defined/exists distinction?
1874
92993692
JH
1875This depends on the tied hash's implementation of EXISTS().
1876For example, there isn't the concept of undef with hashes
1877that are tied to DBM* files. It also means that exists() and
1878defined() do the same thing with a DBM* file, and what they
1879end up doing is not what they do with ordinary hashes.
68dc0745 1880
1881=head2 How do I reset an each() operation part-way through?
1882
5a964f20 1883Using C<keys %hash> in scalar context returns the number of keys in
68dc0745 1884the hash I<and> resets the iterator associated with the hash. You may
1885need to do this if you use C<last> to exit a loop early so that when you
46fc3d4c 1886re-enter it, the hash iterator has been reset.
68dc0745 1887
1888=head2 How can I get the unique keys from two hashes?
1889
d92eb7b0
GS
1890First you extract the keys from the hashes into lists, then solve
1891the "removing duplicates" problem described above. For example:
68dc0745 1892
1893 %seen = ();
1894 for $element (keys(%foo), keys(%bar)) {
1895 $seen{$element}++;
1896 }
1897 @uniq = keys %seen;
1898
1899Or more succinctly:
1900
1901 @uniq = keys %{{%foo,%bar}};
1902
1903Or if you really want to save space:
1904
1905 %seen = ();
1906 while (defined ($key = each %foo)) {
1907 $seen{$key}++;
1908 }
1909 while (defined ($key = each %bar)) {
1910 $seen{$key}++;
1911 }
1912 @uniq = keys %seen;
1913
1914=head2 How can I store a multidimensional array in a DBM file?
1915
1916Either stringify the structure yourself (no fun), or else
1917get the MLDBM (which uses Data::Dumper) module from CPAN and layer
1918it on top of either DB_File or GDBM_File.
1919
1920=head2 How can I make my hash remember the order I put elements into it?
1921
1922Use the Tie::IxHash from CPAN.
1923
46fc3d4c 1924 use Tie::IxHash;
5f8d77f1 1925 tie my %myhash, 'Tie::IxHash';
49d635f9 1926 for (my $i=0; $i<20; $i++) {
46fc3d4c 1927 $myhash{$i} = 2*$i;
1928 }
49d635f9 1929 my @keys = keys %myhash;
46fc3d4c 1930 # @keys = (0,1,2,3,...)
1931
68dc0745 1932=head2 Why does passing a subroutine an undefined element in a hash create it?
1933
1934If you say something like:
1935
1936 somefunc($hash{"nonesuch key here"});
1937
1938Then that element "autovivifies"; that is, it springs into existence
1939whether you store something there or not. That's because functions
1940get scalars passed in by reference. If somefunc() modifies C<$_[0]>,
1941it has to be ready to write it back into the caller's version.
1942
87275199 1943This has been fixed as of Perl5.004.
68dc0745 1944
1945Normally, merely accessing a key's value for a nonexistent key does
1946I<not> cause that key to be forever there. This is different than
1947awk's behavior.
1948
fc36a67e 1949=head2 How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?
68dc0745 1950
65acb1b1
TC
1951Usually a hash ref, perhaps like this:
1952
1953 $record = {
1954 NAME => "Jason",
1955 EMPNO => 132,
1956 TITLE => "deputy peon",
1957 AGE => 23,
1958 SALARY => 37_000,
1959 PALS => [ "Norbert", "Rhys", "Phineas"],
1960 };
1961
1962References are documented in L<perlref> and the upcoming L<perlreftut>.
1963Examples of complex data structures are given in L<perldsc> and
1964L<perllol>. Examples of structures and object-oriented classes are
1965in L<perltoot>.
68dc0745 1966
1967=head2 How can I use a reference as a hash key?
1968
fe854a6f 1969You can't do this directly, but you could use the standard Tie::RefHash
87275199 1970module distributed with Perl.
68dc0745 1971
1972=head1 Data: Misc
1973
1974=head2 How do I handle binary data correctly?
1975
1976Perl is binary clean, so this shouldn't be a problem. For example,
1977this works fine (assuming the files are found):
1978
1979 if (`cat /vmunix` =~ /gzip/) {
1980 print "Your kernel is GNU-zip enabled!\n";
1981 }
1982
d92eb7b0
GS
1983On less elegant (read: Byzantine) systems, however, you have
1984to play tedious games with "text" versus "binary" files. See
49d635f9 1985L<perlfunc/"binmode"> or L<perlopentut>.
68dc0745 1986
1987If you're concerned about 8-bit ASCII data, then see L<perllocale>.
1988
54310121 1989If you want to deal with multibyte characters, however, there are
68dc0745 1990some gotchas. See the section on Regular Expressions.
1991
1992=head2 How do I determine whether a scalar is a number/whole/integer/float?
1993
1994Assuming that you don't care about IEEE notations like "NaN" or
1995"Infinity", you probably just want to use a regular expression.
1996
65acb1b1
TC
1997 if (/\D/) { print "has nondigits\n" }
1998 if (/^\d+$/) { print "is a whole number\n" }
1999 if (/^-?\d+$/) { print "is an integer\n" }
2000 if (/^[+-]?\d+$/) { print "is a +/- integer\n" }
2001 if (/^-?\d+\.?\d*$/) { print "is a real number\n" }
881bdbd4 2002 if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) { print "is a decimal number\n" }
65acb1b1 2003 if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/)
881bdbd4 2004 { print "a C float\n" }
68dc0745 2005
92993692
JH
2006You can also use the L<Data::Types|Data::Types> module on
2007the CPAN, which exports functions that validate data types
f0f835c2
A
2008using these and other regular expressions, or you can use
2009the C<Regexp::Common> module from CPAN which has regular
2010expressions to match various types of numbers.
b5b6f210 2011
5a964f20
TC
2012If you're on a POSIX system, Perl's supports the C<POSIX::strtod>
2013function. Its semantics are somewhat cumbersome, so here's a C<getnum>
2014wrapper function for more convenient access. This function takes
2015a string and returns the number it found, or C<undef> for input that
2016isn't a C float. The C<is_numeric> function is a front end to C<getnum>
2017if you just want to say, ``Is this a float?''
2018
2019 sub getnum {
2020 use POSIX qw(strtod);
2021 my $str = shift;
2022 $str =~ s/^\s+//;
2023 $str =~ s/\s+$//;
2024 $! = 0;
2025 my($num, $unparsed) = strtod($str);
2026 if (($str eq '') || ($unparsed != 0) || $!) {
2027 return undef;
2028 } else {
2029 return $num;
197aec24
RGS
2030 }
2031 }
5a964f20 2032
197aec24 2033 sub is_numeric { defined getnum($_[0]) }
5a964f20 2034
b5b6f210
JH
2035Or you could check out the L<String::Scanf|String::Scanf> module on the CPAN
2036instead. The POSIX module (part of the standard Perl distribution) provides
2037the C<strtod> and C<strtol> for converting strings to double and longs,
6cecdcac 2038respectively.
68dc0745 2039
2040=head2 How do I keep persistent data across program calls?
2041
2042For some specific applications, you can use one of the DBM modules.
fe854a6f
AT
2043See L<AnyDBM_File>. More generically, you should consult the FreezeThaw
2044or Storable modules from CPAN. Starting from Perl 5.8 Storable is part
2045of the standard distribution. Here's one example using Storable's C<store>
2046and C<retrieve> functions:
65acb1b1 2047
197aec24 2048 use Storable;
65acb1b1
TC
2049 store(\%hash, "filename");
2050
197aec24 2051 # later on...
65acb1b1
TC
2052 $href = retrieve("filename"); # by ref
2053 %hash = %{ retrieve("filename") }; # direct to hash
68dc0745 2054
2055=head2 How do I print out or copy a recursive data structure?
2056
65acb1b1 2057The Data::Dumper module on CPAN (or the 5.005 release of Perl) is great
6f82c03a
EM
2058for printing out data structures. The Storable module on CPAN (or the
20595.8 release of Perl), provides a function called C<dclone> that recursively
2060copies its argument.
65acb1b1 2061
197aec24 2062 use Storable qw(dclone);
65acb1b1 2063 $r2 = dclone($r1);
68dc0745 2064
65acb1b1
TC
2065Where $r1 can be a reference to any kind of data structure you'd like.
2066It will be deeply copied. Because C<dclone> takes and returns references,
2067you'd have to add extra punctuation if you had a hash of arrays that
2068you wanted to copy.
68dc0745 2069
65acb1b1 2070 %newhash = %{ dclone(\%oldhash) };
68dc0745 2071
2072=head2 How do I define methods for every class/object?
2073
2074Use the UNIVERSAL class (see L<UNIVERSAL>).
2075
2076=head2 How do I verify a credit card checksum?
2077
2078Get the Business::CreditCard module from CPAN.
2079
65acb1b1
TC
2080=head2 How do I pack arrays of doubles or floats for XS code?
2081
2082The kgbpack.c code in the PGPLOT module on CPAN does just this.
2083If you're doing a lot of float or double processing, consider using
2084the PDL module from CPAN instead--it makes number-crunching easy.
2085
68dc0745 2086=head1 AUTHOR AND COPYRIGHT
2087
0bc0ad85 2088Copyright (c) 1997-2002 Tom Christiansen and Nathan Torkington.
5a964f20
TC
2089All rights reserved.
2090
5a7beb56
JH
2091This documentation is free; you can redistribute it and/or modify it
2092under the same terms as Perl itself.
5a964f20
TC
2093
2094Irrespective of its distribution, all code examples in this file
2095are hereby placed into the public domain. You are permitted and
2096encouraged to use this code in your own programs for fun
2097or for profit as you see fit. A simple comment in the code giving
2098credit would be courteous but is not required.