This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Re: Should keys in pseudo-hashes -always- exist? [DOC PATCH]
[perl5.git] / pod / perlref.pod
index df85013..08a2b42 100644 (file)
@@ -21,7 +21,7 @@ hashes of arrays, arrays of hashes of functions, and so on.
 
 Hard references are smart--they keep track of reference counts for you,
 automatically freeing the thing referred to when its reference count goes
-to zero.  (Note: the reference counts for values in self-referential or
+to zero.  (Reference counts for values in self-referential or
 cyclic data structures may not go to zero without a little help; see
 L<perlobj/"Two-Phased Garbage Collection"> for a detailed explanation.)
 If that thing happens to be an object, the object is destructed.  See
@@ -31,7 +31,7 @@ have been officially "blessed" into a class package.)
 
 Symbolic references are names of variables or other objects, just as a
 symbolic link in a Unix filesystem contains merely the name of a file.
-The C<*glob> notation is a kind of symbolic reference.  (Symbolic
+The C<*glob> notation is something of a of symbolic reference.  (Symbolic
 references are sometimes called "soft references", but please don't call
 them that; references are confusing enough without useless synonyms.)
 
@@ -56,8 +56,8 @@ References can be created in several ways.
 =item 1.
 
 By using the backslash operator on a variable, subroutine, or value.
-(This works much like the & (address-of) operator in C.)  Note
-that this typically creates I<ANOTHER> reference to a variable, because
+(This works much like the & (address-of) operator in C.)  
+This typically creates I<another> reference to a variable, because
 there's already a reference to the variable in the symbol table.  But
 the symbol table reference might go away, and you'll still have the
 reference that the backslash returned.  Here are some examples:
@@ -87,7 +87,7 @@ elements.  (The multidimensional syntax described later can be used to
 access this.  For example, after the above, C<$arrayref-E<gt>[2][1]> would have
 the value "b".)
 
-Note that taking a reference to an enumerated list is not the same
+Taking a reference to an enumerated list is not the same
 as using square brackets--instead it's the same as creating
 a list of references!
 
@@ -136,7 +136,7 @@ On the other hand, if you want the other meaning, you can do this:
     sub showem {       {; @_ } }   # ok
     sub showem { { return @_ } }   # ok
 
-Note how the leading C<+{> and C<{;> always serve to disambiguate
+The leading C<+{> and C<{;> always serve to disambiguate
 the expression to mean either the HASH reference, or the BLOCK.
 
 =item 4.
@@ -146,18 +146,18 @@ C<sub> without a subname:
 
     $coderef = sub { print "Boink!\n" };
 
-Note the presence of the semicolon.  Except for the fact that the code
-inside isn't executed immediately, a C<sub {}> is not so much a
+Note the semicolon.  Except for the code
+inside not being immediately executed, a C<sub {}> is not so much a
 declaration as it is an operator, like C<do{}> or C<eval{}>.  (However, no
 matter how many times you execute that particular line (unless you're in an
-C<eval("...")>), C<$coderef> will still have a reference to the I<SAME>
+C<eval("...")>), $coderef will still have a reference to the I<same>
 anonymous subroutine.)
 
 Anonymous subroutines act as closures with respect to my() variables,
-that is, variables visible lexically within the current scope.  Closure
+that is, variables lexically visible within the current scope.  Closure
 is a notion out of the Lisp world that says if you define an anonymous
 function in a particular lexical context, it pretends to run in that
-context even when it's called outside of the context.
+context even when it's called outside the context.
 
 In human terms, it's a funny way of passing arguments to a subroutine when
 you define it as well as when you call it.  It's useful for setting up
@@ -165,11 +165,9 @@ little bits of code to run later, such as callbacks.  You can even
 do object-oriented stuff with it, though Perl already provides a different
 mechanism to do that--see L<perlobj>.
 
-You can also think of closure as a way to write a subroutine template without
-using eval.  (In fact, in version 5.000, eval was the I<only> way to get
-closures.  You may wish to use "require 5.001" if you use closures.)
-
-Here's a small example of how closures works:
+You might also think of closure as a way to write a subroutine
+template without using eval().  Here's a small example of how
+closures work:
 
     sub newprint {
        my $x = shift;
@@ -188,10 +186,10 @@ This prints
     Howdy, world!
     Greetings, earthlings!
 
-Note particularly that $x continues to refer to the value passed into
-newprint() I<despite> the fact that the "my $x" has seemingly gone out of
-scope by the time the anonymous subroutine runs.  That's what closure
-is all about.
+Note particularly that $x continues to refer to the value passed
+into newprint() I<despite> "my $x" having gone out of scope by the
+time the anonymous subroutine runs.  That's what a closure is all
+about.
 
 This applies only to lexical variables, by the way.  Dynamic variables
 continue to work as they have always worked.  Closure is not something
@@ -200,7 +198,7 @@ that most Perl programmers need trouble themselves about to begin with.
 =item 5.
 
 References are often returned by special subroutines called constructors.
-Perl objects are just references to a special kind of object that happens to know
+Perl objects are just references to a special type of object that happens to know
 which package it's associated with.  Constructors are just special
 subroutines that know how to create that association.  They do so by
 starting with an ordinary reference, and it remains an ordinary reference
@@ -241,35 +239,37 @@ known as foo).
     $ioref     = *STDIN{IO};
     $globref   = *foo{GLOB};
 
-All of these are self-explanatory except for *foo{IO}.  It returns the
-IO handle, used for file handles (L<perlfunc/open>), sockets
-(L<perlfunc/socket> and L<perlfunc/socketpair>), and directory handles
-(L<perlfunc/opendir>).  For compatibility with previous versions of
-Perl, *foo{FILEHANDLE} is a synonym for *foo{IO}.
+All of these are self-explanatory except for C<*foo{IO}>.  It returns
+the IO handle, used for file handles (L<perlfunc/open>), sockets
+(L<perlfunc/socket> and L<perlfunc/socketpair>), and directory
+handles (L<perlfunc/opendir>).  For compatibility with previous
+versions of Perl, C<*foo{FILEHANDLE}> is a synonym for C<*foo{IO}>.
 
-*foo{THING} returns undef if that particular THING hasn't been used yet,
-except in the case of scalars.  *foo{SCALAR} returns a reference to an
+C<*foo{THING}> returns undef if that particular THING hasn't been used yet,
+except in the case of scalars.  C<*foo{SCALAR}> returns a reference to an
 anonymous scalar if $foo hasn't been used yet.  This might change in a
 future release.
 
-*foo{IO} is an alternative to the \*HANDLE mechanism given in
+C<*foo{IO}> is an alternative to the C<*HANDLE> mechanism given in
 L<perldata/"Typeglobs and Filehandles"> for passing filehandles
 into or out of subroutines, or storing into larger data structures.
 Its disadvantage is that it won't create a new filehandle for you.
-Its advantage is that you have no risk of clobbering more than you want
-to with a typeglob assignment, although if you assign to a scalar instead
-of a typeglob, you're ok.
+Its advantage is that you have less risk of clobbering more than
+you want to with a typeglob assignment.  (It still conflates file
+and directory handles, though.)  However, if you assign the incoming
+value to a scalar instead of a typeglob as we do in the examples
+below, there's no risk of that happening.
 
-    splutter(*STDOUT);
-    splutter(*STDOUT{IO});
+    splutter(*STDOUT);         # pass the whole glob
+    splutter(*STDOUT{IO});     # pass both file and dir handles
 
     sub splutter {
        my $fh = shift;
        print $fh "her um well a hmmm\n";
     }
 
-    $rec = get_rec(*STDIN);
-    $rec = get_rec(*STDIN{IO});
+    $rec = get_rec(*STDIN);    # pass the whole glob
+    $rec = get_rec(*STDIN{IO}); # pass both file and dir handles
 
     sub get_rec {
        my $fh = shift;
@@ -299,9 +299,9 @@ a simple scalar variable containing a reference of the correct type:
     &$coderef(1,2,3);
     print $globref "output\n";
 
-It's important to understand that we are specifically I<NOT> dereferencing
+It's important to understand that we are specifically I<not> dereferencing
 C<$arrayref[0]> or C<$hashref{"KEY"}> there.  The dereference of the
-scalar variable happens I<BEFORE> it does any key lookups.  Anything more
+scalar variable happens I<before> it does any key lookups.  Anything more
 complicated than a simple scalar variable must use methods 2 or 3 below.
 However, a "simple scalar" includes an identifier that itself uses method
 1 recursively.  Therefore, the following prints "howdy".
@@ -334,7 +334,7 @@ people often make the mistake of viewing the dereferencing symbols as
 proper operators, and wonder about their precedence.  If they were,
 though, you could use parentheses instead of braces.  That's not the case.
 Consider the difference below; case 0 is a short-hand version of case 1,
-I<NOT> case 2:
+I<not> case 2:
 
     $$hashref{"KEY"}   = "VALUE";      # CASE 0
     ${$hashref}{"KEY"} = "VALUE";      # CASE 1
@@ -356,7 +356,7 @@ syntactic sugar, the examples for method 2 may be written:
     $coderef->(1,2,3);            # Subroutine call
 
 The left side of the arrow can be any expression returning a reference,
-including a previous dereference.  Note that C<$array[$x]> is I<NOT> the
+including a previous dereference.  Note that C<$array[$x]> is I<not> the
 same thing as C<$array-E<gt>[$x]> here:
 
     $array[$x]->{"foo"}->[0] = "January";
@@ -369,7 +369,7 @@ C<{"foo"}> in it.  Likewise C<$array[$x]-E<gt>{"foo"}> will automatically get
 defined with an array reference so that we can look up C<[0]> in it.
 This process is called I<autovivification>.
 
-One more thing here.  The arrow is optional I<BETWEEN> brackets
+One more thing here.  The arrow is optional I<between> brackets
 subscripts, so you can shrink the above down to
 
     $array[$x]{"foo"}[0] = "January";
@@ -394,14 +394,27 @@ civility though.
 
 =back
 
-The ref() operator may be used to determine what type of thing the
-reference is pointing to.  See L<perlfunc>.
+Using a string or number as a reference produces a symbolic reference,
+as explained above.  Using a reference as a number produces an
+integer representing its storage location in memory.  The only
+useful thing to be done with this is to compare two references
+numerically to see whether they refer to the same location.
+
+    if ($ref1 == $ref2) {  # cheap numeric compare of references
+       print "refs 1 and 2 refer to the same thing\n";
+    }
+
+Using a reference as a string produces both its referent's type,
+including any package blessing as described in L<perlobj>, as well
+as the numeric address expressed in hex.  The ref() operator returns
+just the type of thing the reference is pointing to, without the
+address.  See L<perlfunc/ref> for details and examples of its use.
 
 The bless() operator may be used to associate the object a reference
 points to with a package functioning as an object class.  See L<perlobj>.
 
 A typeglob may be dereferenced the same way a reference can, because
-the dereference syntax always indicates the kind of reference desired.
+the dereference syntax always indicates the type of reference desired.
 So C<${*foo}> and C<${\$foo}> both indicate the same scalar variable.
 
 Here's a trick for interpolating a subroutine call into a string:
@@ -421,9 +434,9 @@ chicanery is also useful for arbitrary expressions:
 
 We said that references spring into existence as necessary if they are
 undefined, but we didn't say what happens if a value used as a
-reference is already defined, but I<ISN'T> a hard reference.  If you
-use it as a reference in this case, it'll be treated as a symbolic
-reference.  That is, the value of the scalar is taken to be the I<NAME>
+reference is already defined, but I<isn't> a hard reference.  If you
+use it as a reference, it'll be treated as a symbolic
+reference.  That is, the value of the scalar is taken to be the I<name>
 of a variable, rather than a direct link to a (possibly) anonymous
 value.
 
@@ -439,7 +452,7 @@ People frequently expect it to work like this.  So it does.
     $pack = "THAT";
     ${"${pack}::$name"} = 5;   # Sets $THAT::foo without eval
 
-This is very powerful, and slightly dangerous, in that it's possible
+This is powerful, and slightly dangerous, in that it's possible
 to intend (with the utmost sincerity) to use a hard reference, and
 accidentally use a symbolic reference instead.  To protect against
 that, you can say
@@ -456,7 +469,7 @@ symbolic references.  Lexical variables (declared with my()) aren't in
 a symbol table, and thus are invisible to this mechanism.  For example:
 
     local $value = 10;
-    $ref = \$value;
+    $ref = "value";
     {
        my $value = 20;
        print $$ref;
@@ -474,7 +487,7 @@ always have within a string.  That is,
     $push = "pop on ";
     print "${push}over";
 
-has always meant to print "pop on over", despite the fact that push is
+has always meant to print "pop on over", even though push is
 a reserved word.  This has been generalized to work the same outside
 of quotes, so that
 
@@ -485,7 +498,7 @@ and even
     print ${ push } . "over";
 
 will have the same effect.  (This would have been a syntax error in
-Perl 5.000, though Perl 4 allowed it in the spaceless form.)  Note that this
+Perl 5.000, though Perl 4 allowed it in the spaceless form.)  This
 construct is I<not> considered to be a symbolic reference when you're
 using strict refs:
 
@@ -521,10 +534,10 @@ string is effectively quoted.
 
 =head2 Pseudo-hashes: Using an array as a hash
 
-WARNING:  This section describes an experimental feature.  Details may
+B<WARNING>:  This section describes an experimental feature.  Details may
 change without notice in future versions.
 
-Beginning with release 5.005 of Perl you can use an array reference
+Beginning with release 5.005 of Perl, you may use an array reference
 in some contexts that would normally require a hash reference.  This
 allows you to access array elements using symbolic names, as if they
 were fields in a structure.
@@ -550,6 +563,24 @@ or try to access nonexistent fields.  For better performance, Perl can also
 do the translation from field names to array indices at compile time for
 typed object references.  See L<fields>.
 
+There are two ways to check for the existance of a key in a
+pseudo-hash.  The first is to use exists().  This checks to see if the
+given field has been used yet.  It acts this way to match the behavior
+of a regular hash.  For instance:
+
+       $phash = [{foo =>, bar => 2, pants => 3}, 'FOO'];
+       $phash->{pants} = undef;
+
+       exists $phash->{foo};    # true, 'foo' was set in the declaration
+       exists $phash->{bar};    # false, 'bar' has not been used.
+       exists $phash->{pants};  # true, your 'pants' have been touched
+
+The second is to use exists() on the hash reference sitting in the
+first array element.  This checks to see if the given key is a valid
+field in the pseudo-hash.
+
+       exists $phash->[0]{pants};      # true, 'pants' is a valid field
+       exists $phash->[0]{shoes};      # false, 'shoes' can't be used
 
 =head2 Function Templates
 
@@ -564,7 +595,7 @@ that generated HTML font changes for the various colors:
 
     print "Be ", red("careful"), "with that ", green("light");
 
-The red() and green() functions would be very similar.  To create these,
+The red() and green() functions would be similar.  To create these,
 we'll assign a closure to a typeglob of the name of the function we're
 trying to build.  
 
@@ -598,7 +629,7 @@ above--only works with closures, not general subroutines.  In the general
 case, then, named subroutines do not nest properly, although anonymous
 ones do.  If you are accustomed to using nested subroutines in other
 programming languages with their own private variables, you'll have to
-work at it a bit in Perl.  The intuitive coding of this kind of thing
+work at it a bit in Perl.  The intuitive coding of this type of thing
 incurs mysterious warnings about ``will not stay shared''.  For example,
 this won't work:
 
@@ -646,7 +677,7 @@ The standard Tie::RefHash module provides a convenient workaround to this.
 =head1 SEE ALSO
 
 Besides the obvious documents, source code can be instructive.
-Some rather pathological examples of the use of references can be found
+Some pathological examples of the use of references can be found
 in the F<t/op/ref.t> regression test in the Perl source directory.
 
 See also L<perldsc> and L<perllol> for how to use references to create