2009/12/16 Bryan R Harris <bryan_r_har...@raytheon.com>: > What's the difference between pointers and references? Where can I read > about that difference?
The key difference in my mind is this: Perl references are defined in terms of perl datatypes. C pointers are defined (more or less) in terms of memory locations. If you think about Perl references in terms of *what they do* and not *how they work*, it becomes much clearer. There is nothing you can do to a perl reference to get its "memory address", so that doesn't fit within the conceptual framework of Perl references. Perl references are simply scalar values which provide an indirect form of access to other perl objects (including scalars, hashes, OO types...). You can create a reference from a named or anonymous variable, and you can dereference that reference to get the original object. You can think of them as labels or tags or handles; all of these ideas fit the paradigm created by the interface of the reference. C pointers, however, let you do so much more, most of it unsafe. They let you add arbitrary integers to pointers; this may well end up with an invalid pointer value. They let you subtract one pointer from another to find out the distance in memory locations between object A and object B. The interface suggests that a pointer is a memory location value, much more than a label on a variable. Note that this thinking in terms of what it does applies to other datatypes. For example: the CGI module is a module which helps write CGI scripts. It emits HTTP headers and lets you write HTML in a Perl-like way. As a user of this module, you don't start with implementation details such as "The CGI module stores state about the HTTP connection to determine which MIME types the client can read. To parse this Content-Accept: header, it uses the following regexes..." Instead, you talk about what it does: $q = CGI->new; # create new CGI object print $q->header, # create the HTTP header $q->start_html('hello world'), # start the HTML $q->h1('hello world'), # level 1 header $q->end_html; # end the HTML The same thinking applies to references: forget about what they are under the hood. Think only in terms of what they do. > If the data structures being referenced (?) by those references are created > within the subroutine with "my", are they still alive and accessible outside > the subroutine? Or do they go away after you return? They're still alive. Perl objects are not harvested by the GC until there are no more references to them. So this is perfectly safe: sub anon_scalar { my $x; return \$x} my $ref = anon_scalar; $$ref = 3; Phil -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/