Restore mmap function (broken by tweaks to shared buffer
[p5sagit/p5-mst-13.2.git] / pod / perlfaq4.pod
index 700c42a..23bc666 100644 (file)
@@ -4,7 +4,7 @@ perlfaq4 - Data Manipulation ($Revision: 1.49 $, $Date: 1999/05/23 20:37:49 $)
 
 =head1 DESCRIPTION
 
-The section of the FAQ answers question related to the manipulation
+The section of the FAQ answers questions related to the manipulation
 of data as numbers, dates, strings, arrays, hashes, and miscellaneous
 data issues.
 
@@ -13,13 +13,13 @@ data issues.
 =head2 Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?
 
 The infinite set that a mathematician thinks of as the real numbers can
-only be approximate on a computer, since the computer only has a finite
+only be approximated on a computer, since the computer only has a finite
 number of bits to store an infinite number of, um, numbers.
 
 Internally, your computer represents floating-point numbers in binary.
 Floating-point numbers read in from a file or appearing as literals
 in your program are converted from their decimal floating-point
-representation (eg, 19.95) to the internal binary representation.
+representation (eg, 19.95) to an internal binary representation.
 
 However, 19.95 can't be precisely represented as a binary
 floating-point number, just like 1/3 can't be exactly represented as a
@@ -29,9 +29,9 @@ of 19.95, therefore, isn't exactly 19.95.
 When a floating-point number gets printed, the binary floating-point
 representation is converted back to decimal.  These decimal numbers
 are displayed in either the format you specify with printf(), or the
-current output format for numbers (see L<perlvar/"$#"> if you use
+current output format for numbers.  (See L<perlvar/"$#"> if you use
 print.  C<$#> has a different default value in Perl5 than it did in
-Perl4.  Changing C<$#> yourself is deprecated.
+Perl4.  Changing C<$#> yourself is deprecated.)
 
 This affects B<all> computer languages that represent decimal
 floating-point numbers in binary, not just Perl.  Perl provides
@@ -67,7 +67,7 @@ route.
 
     printf("%.3f", 3.1415926535);      # prints 3.142
 
-The POSIX module (part of the standard perl distribution) implements
+The POSIX module (part of the standard Perl distribution) implements
 ceil(), floor(), and a number of other mathematical and trigonometric
 functions.
 
@@ -75,8 +75,8 @@ functions.
     $ceil   = ceil(3.5);                       # 4
     $floor  = floor(3.5);                      # 3
 
-In 5.000 to 5.003 Perls, trigonometry was done in the Math::Complex
-module.  With 5.004, the Math::Trig module (part of the standard perl
+In 5.000 to 5.003 perls, trigonometry was done in the Math::Complex
+module.  With 5.004, the Math::Trig module (part of the standard Perl
 distribution) implements the trigonometric functions. Internally it
 uses the Math::Complex module and some functions can break out from
 the real axis into the complex plane, for example the inverse sine of
@@ -105,12 +105,12 @@ are not guaranteed.
 
 To turn a string of 1s and 0s like C<10110110> into a scalar containing
 its binary value, use the pack() and unpack() functions (documented in
-L<perlfunc/"pack" L<perlfunc/"unpack">):
+L<perlfunc/"pack"> and L<perlfunc/"unpack">):
 
     $decimal = unpack('c', pack('B8', '10110110'));
 
 This packs the string C<10110110> into an eight bit binary structure.
-This is then unpack as a character, which returns its ordinal value.
+This is then unpacked as a character, which returns its ordinal value.
 
 This does the same thing:
 
@@ -183,6 +183,15 @@ ranges.  Instead use:
         push(@results, some_func($i));
     }
 
+This situation has been fixed in Perl5.005. Use of C<..> in a C<for>
+loop will iterate over the range, without creating the entire range.
+
+    for my $i (5 .. 500_005) {
+        push(@results, some_func($i));
+    }
+
+will not create a list of 500,000 integers.
+
 =head2 How can I output Roman numerals?
 
 Get the http://www.perl.com/CPAN/modules/by-module/Roman module.
@@ -197,8 +206,8 @@ than more.
 
 Computers are good at being predictable and bad at being random
 (despite appearances caused by bugs in your programs :-).
-http://www.perl.com/CPAN/doc/FMTEYEWTK/random, courtesy of Tom
-Phoenix, talks more about this..  John von Neumann said, ``Anyone who
+http://www.perl.com/CPAN/doc/FMTEYEWTK/random , courtesy of Tom
+Phoenix, talks more about this.  John von Neumann said, ``Anyone who
 attempts to generate random numbers by deterministic means is, of
 course, living in a state of sin.''
 
@@ -273,11 +282,11 @@ and Date::Manip modules from CPAN.
 
 =head2 How can I find the Julian Day?
 
-You could use Date::Calc's Delta_Days function and calculate the number
-of days from there.  Assuming that's what you really want, that is.
+Use the Time::JulianDay module (part of the Time-modules bundle
+available from CPAN.)
 
 Before you immerse yourself too deeply in this, be sure to verify that it
-is the I<Julian> Day you really want.  Are they really just interested in
+is the I<Julian> Day you really want.  Are you really just interested in
 a way of getting serial days so that they can do date arithmetic?  If you
 are interested in performing date arithmetic, this can be done using
 either Date::Manip or Date::Calc, without converting to Julian Day first.
@@ -292,9 +301,6 @@ world and 1980 in the MS-DOS/Windows world.  If you find that it is not
 the first meaning that you really want, then check out the Date::Manip
 and Date::Calc modules.  (Thanks to David Cassell for most of this text.)
 
-There is also an example of Julian date calculation that should help you in
-http://www.perl.com/CPAN/authors/David_Muir_Sharnoff/modules/Time/JulianDay.pm.gz
-
 =head2 How do I find yesterday's date?
 
 The C<time()> function returns the current time in seconds since the
@@ -333,7 +339,7 @@ A solution to this issue is offered by Russ Allbery.
     #
     # The explicit settings of $ndst and $tdst are necessary because localtime
     # only says it returns the system tm struct, and the system tm struct at
-    # least on Solaris doesn't guarantee any particuliar positive value (like,
+    # least on Solaris doesn't guarantee any particular positive value (like,
     # say, 1) for isdst, just a positive value.  And that value can
     # potentially be negative, if DST information isn't available (this sub
     # just treats those cases like no DST).
@@ -350,7 +356,7 @@ A solution to this issue is offered by Russ Allbery.
     # Copyright relinquished 1999 by Russ Allbery <rra@stanford.edu>
     # This code is in the public domain
 
-=head2 Does Perl have a year 2000 problem?  Is Perl Y2K compliant?
+=head2 Does Perl have a Year 2000 problem?  Is Perl Y2K compliant?
 
 Short answer: No, Perl does not have a Year 2000 problem.  Yes, Perl is
 Y2K compliant (whatever that means).  The programmers you've hired to
@@ -361,10 +367,10 @@ Perl is just as Y2K compliant as your pencil--no more, and no less.
 Can you use your pencil to write a non-Y2K-compliant memo?  Of course
 you can.  Is that the pencil's fault?  Of course it isn't.
 
-The date and time functions supplied with perl (gmtime and localtime)
+The date and time functions supplied with Perl (gmtime and localtime)
 supply adequate information to determine the year well beyond 2000
 (2038 is when trouble strikes for 32-bit machines).  The year returned
-by these functions when used in an array context is the year minus 1900.
+by these functions when used in a list context is the year minus 1900.
 For years between 1910 and 1999 this I<happens> to be a 2-digit decimal
 number. To avoid the year 2000 problem simply do not treat the year as
 a 2-digit number.  It isn't.
@@ -392,7 +398,7 @@ addresses, etc.) for details.
 
 It depends just what you mean by ``escape''.  URL escapes are dealt
 with in L<perlfaq9>.  Shell escapes with the backslash (C<\>)
-character are removed with:
+character are removed with
 
     s/\\(.)/$1/g;
 
@@ -438,11 +444,9 @@ nested patterns, nor can they.  For that you'll have to write a
 parser.
 
 If you are serious about writing a parser, there are a number of
-modules or oddities that will make your life a lot easier.  There is
-the CPAN module Parse::RecDescent, the standard module Text::Balanced,
-the byacc program, the CPAN module Parse::Yapp, and Mark-Jason
-Dominus's excellent I<py> tool at http://www.plover.com/~mjd/perl/py/
-.
+modules or oddities that will make your life a lot easier.  There are
+the CPAN modules Parse::RecDescent, Parse::Yapp, and Text::Balanced;
+and the byacc program.
 
 One simple destructive, inside-out approach that you might try is to
 pull out the smallest nesting parts one at a time:
@@ -459,7 +463,7 @@ really does work:
     # $_ contains the string to parse
     # BEGIN and END are the opening and closing markers for the
     # nested text.
+
     @( = ('(','');
     @) = (')','');
     ($re=$_)=~s/((BEGIN)|(END)|.)/$)[!$3]\Q$1\E$([!$2]/gs;
@@ -479,7 +483,7 @@ You can do it yourself:
 
     1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
 
-Or you can just use the Text::Tabs module (part of the standard perl
+Or you can just use the Text::Tabs module (part of the standard Perl
 distribution).
 
     use Text::Tabs;
@@ -487,7 +491,7 @@ distribution).
 
 =head2 How do I reformat a paragraph?
 
-Use Text::Wrap (part of the standard perl distribution):
+Use Text::Wrap (part of the standard Perl distribution):
 
     use Text::Wrap;
     print wrap("\t", '  ', @paragraphs);
@@ -508,7 +512,7 @@ use substr() as an lvalue:
     substr($a, 0, 3) = "Tom";
 
 Although those with a pattern matching kind of thought process will
-likely prefer:
+likely prefer
 
     $a =~ s/^.../Tom/;
 
@@ -545,7 +549,7 @@ repetition count and repeated pattern like this:
 
 =head2 How can I count the number of occurrences of a substring within a string?
 
-There are a number of ways, with varying efficiency: If you want a
+There are a number of ways, with varying efficiency.  If you want a
 count of a certain single character (X) within a string, you can use the
 C<tr///> function like so:
 
@@ -570,8 +574,8 @@ To make the first letter of each word upper case:
         $line =~ s/\b(\w)/\U$1/g;
 
 This has the strange effect of turning "C<don't do it>" into "C<Don'T
-Do It>".  Sometimes you might want this, instead (Suggested by Brian
-Foy):
+Do It>".  Sometimes you might want this.  Other times you might need a
+more thorough solution (Suggested by brian d.  foy):
 
     $string =~ s/ (
                  (^\w)    #at the beginning of the line
@@ -627,21 +631,21 @@ quotation-mark-delimited field, escape them with backslashes (eg,
 C<"like \"this\"">.  Unescaping them is a task addressed earlier in
 this section.
 
-Alternatively, the Text::ParseWords module (part of the standard perl
+Alternatively, the Text::ParseWords module (part of the standard Perl
 distribution) lets you say:
 
     use Text::ParseWords;
     @new = quotewords(",", 0, $text);
 
-There's also a Text::CSV module on CPAN.
+There's also a Text::CSV (Comma-Separated Values) module on CPAN.
 
 =head2 How do I strip blank space from the beginning/end of a string?
 
-Although the simplest approach would seem to be:
+Although the simplest approach would seem to be
 
     $string =~ s/^\s*(.*?)\s*$/$1/;
 
-Not only is this unnecessarily slow and destructive, it also fails with
+not only is this unnecessarily slow and destructive, it also fails with
 embedded newlines.  It is much faster to do this operation in two steps:
 
     $string =~ s/^\s+//;
@@ -735,8 +739,8 @@ you can use this kind of thing:
 
 =head2 How do I find the soundex value of a string?
 
-Use the standard Text::Soundex module distributed with perl.
-But before you do so, you may want to determine whether `soundex' is in
+Use the standard Text::Soundex module distributed with Perl.
+Before you do so, you may want to determine whether `soundex' is in
 fact what you think it is.  Knuth's soundex algorithm compresses words
 into a small space, and so it does not necessarily distinguish between
 two words which you might want to appear separately.  For example, the
@@ -775,9 +779,9 @@ of the FAQ.
 
 =head2 What's wrong with always quoting "$vars"?
 
-The problem is that those double-quotes force stringification,
-coercing numbers and references into strings, even when you
-don't want them to be.  Think of it this way: double-quote
+The problem is that those double-quotes force stringification--
+coercing numbers and references into strings--even when you
+don't want them to be strings.  Think of it this way: double-quote
 expansion is used to produce new strings.  If you already 
 have a string, why do you need more?
 
@@ -815,7 +819,7 @@ Stringification also destroys arrays.
     print "@lines";            # WRONG - extra blanks
     print @lines;              # right
 
-=head2 Why don't my E<lt>E<lt>HERE documents work?
+=head2 Why don't my <<HERE documents work?
 
 Check for these three things:
 
@@ -853,13 +857,13 @@ in the indentation.
 A nice general-purpose fixer-upper function for indented here documents
 follows.  It expects to be called with a here document as its argument.
 It looks to see whether each line begins with a common substring, and
-if so, strips that off.  Otherwise, it takes the amount of leading
-white space found on the first line and removes that much off each
+if so, strips that substring off.  Otherwise, it takes the amount of leading
+whitespace found on the first line and removes that much off each
 subsequent line.
 
     sub fix {
         local $_ = shift;
-        my ($white, $leader);  # common white space and common leading string
+        my ($white, $leader);  # common whitespace and common leading string
         if (/^\s*(?:([^\w\s]+)(\s*).*\n)(?:\s*\1\2?.*\n)+$/) {
             ($white, $leader) = ($2, quotemeta($1));
         } else {
@@ -882,7 +886,7 @@ This works with leading special strings, dynamically determined:
        @@@ }
     MAIN_INTERPRETER_LOOP
 
-Or with a fixed amount of leading white space, with remaining
+Or with a fixed amount of leading whitespace, with remaining
 indentation correctly preserved:
 
     $poem = fix<<EVER_ON_AND_ON;
@@ -906,7 +910,7 @@ Subroutines are passed and return lists, you put things into list
 context, you initialize arrays with lists, and you foreach() across
 a list.  C<@> variables are arrays, anonymous arrays are arrays, arrays
 in scalar context behave like the number of elements in them, subroutines
-access their arguments through the array C<@_>, push/pop/shift only work
+access their arguments through the array C<@_>, and push/pop/shift only work
 on arrays.
 
 As a side note, there's no such thing as a list in scalar context.
@@ -920,7 +924,7 @@ last value to be returned: 9.
 
 =head2 What is the difference between $array[1] and @array[1]?
 
-The former is a scalar value, the latter an array slice, which makes
+The former is a scalar value; the latter an array slice, making
 it a list with one (scalar) value.  You should use $ when you want a
 scalar value (most of the time) and @ when you want a list with one
 scalar value in it (very, very rarely; nearly never, in fact).
@@ -934,7 +938,8 @@ with
 
     @bad[0]  = `same program that outputs several lines`;
 
-The B<-w> flag will warn you about these matters.
+The C<use warnings> pragma and the B<-w> flag will warn you about these 
+matters.
 
 =head2 How can I remove duplicate elements from a list or array?
 
@@ -947,12 +952,12 @@ ordered and whether you wish to preserve the ordering.
 (this assumes all true values in the array)
 
     $prev = 'nonesuch';
-    @out = grep($_ ne $prev && ($prev = $_), @in);
+    @out = grep($_ ne $prev && ($prev = $_, 1), @in);
 
 This is nice in that it doesn't use much extra memory, simulating
-uniq(1)'s behavior of removing only adjacent duplicates.  It's less
-nice in that it won't work with false values like undef, 0, or "";
-"0 but true" is ok, though.
+uniq(1)'s behavior of removing only adjacent duplicates.  The ", 1"
+guarantees that the expression is true (so that grep picks it up)
+even if the $_ is 0, "", or undef.
 
 =item b) If you don't know whether @in is sorted:
 
@@ -973,7 +978,7 @@ nice in that it won't work with false values like undef, 0, or "";
 
     undef @ary;
     @ary[@in] = @in;
-    @out = @ary;
+    @out = grep {defined} @ary;
 
 =back
 
@@ -1018,11 +1023,11 @@ Now check whether C<vec($read,$n,1)> is true for some C<$n>.
 
 Please do not use
 
-    $is_there = grep $_ eq $whatever, @array;
+    ($is_there) = grep $_ eq $whatever, @array;
 
 or worse yet
 
-    $is_there = grep /$whatever/, @array;
+    ($is_there) = grep /$whatever/, @array;
 
 These are slow (checks every element even if the first matches),
 inefficient (same reason), and potentially buggy (what if there are
@@ -1052,7 +1057,7 @@ each element is unique in a given array:
     }
 
 Note that this is the I<symmetric difference>, that is, all elements in
-either A or in B, but not in both.  Think of it as an xor operation.
+either A or in B but not in both.  Think of it as an xor operation.
 
 =head2 How do I test whether two arrays or hashes are equal?
 
@@ -1064,7 +1069,7 @@ strings.  Modify if you have other needs.
 
     sub compare_arrays {
        my ($first, $second) = @_;
-       local $^W = 0;  # silence spurious -w undef complaints
+       no warnings;  # silence spurious -w undef complaints
        return 0 unless @$first == @$second;
        for (my $i = 0; $i < @$first; $i++) {
            return 0 if $first->[$i] ne $second->[$i];
@@ -1121,7 +1126,7 @@ Now C<$found_index> has what you want.
 In general, you usually don't need a linked list in Perl, since with
 regular arrays, you can push and pop or shift and unshift at either end,
 or you can use splice to add and/or remove arbitrary number of elements at
-arbitrary points.  Both pop and shift are both O(1) operations on perl's
+arbitrary points.  Both pop and shift are both O(1) operations on Perl's
 dynamic arrays.  In the absence of shifts and pops, push in general
 needs to reallocate on the order every log(N) times, and unshift will
 need to copy pointers each time.
@@ -1143,7 +1148,7 @@ You could walk the list this way:
     }
     print "\n";
 
-You could grow the list this way:
+You could add to the list this way:
 
     my ($head, $tail);
     $tail = append($head, 1);       # grow a new head
@@ -1184,7 +1189,6 @@ Use this:
         my $i;
         for ($i = @$array; --$i; ) {
             my $j = int rand ($i+1);
-            next if $i == $j;
             @$array[$i,$j] = @$array[$j,$i];
         }
     }
@@ -1192,7 +1196,7 @@ Use this:
     fisher_yates_shuffle( \@array );    # permutes @array in place
 
 You've probably seen shuffling algorithms that work using splice,
-randomly picking another element to swap the current element with:
+randomly picking another element to swap the current element with
 
     srand;
     @new = ();
@@ -1276,7 +1280,7 @@ Supply a comparison function to sort() (described in L<perlfunc/sort>):
     @list = sort { $a <=> $b } @list;
 
 The default sort function is cmp, string comparison, which would
-sort C<(1, 2, 10)> into C<(1, 10, 2)>.  C<E<lt>=E<gt>>, used above, is
+sort C<(1, 2, 10)> into C<(1, 10, 2)>.  C<< <=> >>, used above, is
 the numerical comparison operator.
 
 If you have a complicated function needed to pull out the part you
@@ -1293,7 +1297,7 @@ case-insensitively.
     }
     @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];
 
-Which could also be written this way, using a trick
+which could also be written this way, using a trick
 that's come to be known as the Schwartzian Transform:
 
     @sorted = map  { $_->[0] }
@@ -1427,14 +1431,14 @@ sorting the keys as shown in an earlier question.
 Don't do that. :-)
 
 [lwall] In Perl 4, you were not allowed to modify a hash at all while
-interating over it.  In Perl 5 you can delete from it, but you still
+iterating over it.  In Perl 5 you can delete from it, but you still
 can't add to it, because that might cause a doubling of the hash table,
 in which half the entries get copied up to the new top half of the
-table, at which point you've totally bamboozled the interator code.
+table, at which point you've totally bamboozled the iterator code.
 Even if the table doesn't double, there's no telling whether your new
 entry will be inserted before or after the current iterator position.
 
-Either treasure up your changes and make them after the iterator finishes,
+Either treasure up your changes and make them after the iterator finishes
 or use keys to fetch all the old keys at once, and iterate over the list
 of keys.
 
@@ -1467,7 +1471,7 @@ take the scalar sense of the keys() function:
 
     $num_keys = scalar keys %hash;
 
-In void context, the keys() function just resets the iterator, which is
+The keys() function also resets the iterator, which in void context is
 faster for tied hashes than would be iterating through the whole 
 hash, one key-value pair at a time.
 
@@ -1483,8 +1487,8 @@ keys or values:
            } keys %hash;       # and by value
 
 Here we'll do a reverse numeric sort by value, and if two keys are
-identical, sort by length of key, and if that fails, by straight ASCII
-comparison of the keys (well, possibly modified by your locale -- see
+identical, sort by length of key, or if that fails, by straight ASCII
+comparison of the keys (well, possibly modified by your locale--see
 L<perllocale>).
 
     @keys = sort {
@@ -1527,7 +1531,7 @@ And these conditions hold
        $ary{'d'}                       is false
        defined $ary{'d'}               is true
        defined $ary{'a'}               is true
-       exists $ary{'a'}                is true (perl5 only)
+       exists $ary{'a'}                is true (Perl5 only)
        grep ($_ eq 'a', keys %ary)     is true
 
 If you now say
@@ -1551,7 +1555,7 @@ and these conditions now hold; changes in caps:
        $ary{'d'}                       is false
        defined $ary{'d'}               is true
        defined $ary{'a'}               is FALSE
-       exists $ary{'a'}                is true (perl5 only)
+       exists $ary{'a'}                is true (Perl5 only)
        grep ($_ eq 'a', keys %ary)     is true
 
 Notice the last two: you have an undef value, but a defined key!
@@ -1575,7 +1579,7 @@ and these conditions now hold; changes in caps:
        $ary{'d'}                       is false
        defined $ary{'d'}               is true
        defined $ary{'a'}               is false
-       exists $ary{'a'}                is FALSE (perl5 only)
+       exists $ary{'a'}                is FALSE (Perl5 only)
        grep ($_ eq 'a', keys %ary)     is FALSE
 
 See, the whole entry is gone!
@@ -1651,7 +1655,7 @@ whether you store something there or not.  That's because functions
 get scalars passed in by reference.  If somefunc() modifies C<$_[0]>,
 it has to be ready to write it back into the caller's version.
 
-This has been fixed as of perl5.004.
+This has been fixed as of Perl5.004.
 
 Normally, merely accessing a key's value for a nonexistent key does
 I<not> cause that key to be forever there.  This is different than
@@ -1678,7 +1682,7 @@ in L<perltoot>.
 =head2 How can I use a reference as a hash key?
 
 You can't do this directly, but you could use the standard Tie::Refhash
-module distributed with perl.
+module distributed with Perl.
 
 =head1 Data: Misc
 
@@ -1737,13 +1741,12 @@ if you just want to say, ``Is this a float?''
         } 
     } 
 
-    sub is_numeric { defined &getnum } 
+    sub is_numeric { defined getnum($_[0]) } 
 
-Or you could check out
-http://www.perl.com/CPAN/modules/by-module/String/String-Scanf-1.1.tar.gz
-instead.  The POSIX module (part of the standard Perl distribution)
-provides the C<strtol> and C<strtod> for converting strings to double
-and longs, respectively.
+Or you could check out the String::Scanf module on CPAN instead.  The
+POSIX module (part of the standard Perl distribution) provides the
+C<strtod> and C<strtol> for converting strings to double and longs,
+respectively.
 
 =head2 How do I keep persistent data across program calls?