referencing, closures, classes

D

David McDivitt

I am new to Perl going through the book by Deitel, "Perl How to Program". I
went through the first half the book pretty fast and only did a few of the
programming examples to understand. I even made a good application with what
I read this far having four web pages, CGI functionality, functions, hashes,
Perl default variables, and code optimizations.

I seem to be stuck on the conceptual matter of referencing, closures, and
classes. The book is good to the extent it covers the whole language and
represents a good plan for learning the language. Unfortunately, I have
found the book lacking in description of a few key points. They are glossed
over with sentences lacking sufficient detail or are ambiguous. It is as if
the author is impatient to move on. Not only am I learning the language
myself to write production applications, but I am also leaving behind a
methodology for others here to follow. When parts of the book need
clarification I find it for my own benefit, then create a text document
having the problem chapter and section. It is my hope others can go through
the book and read these little text files for clarification when necessary.

I don't like to assume things, and I don't like to do things just because
the book or so-and-so says so. I have read several articles on referencing,
closures, and classes, but am unable to understand exactly why it works and
what Perl is doing with these. I could move on in the book then get what I
want through osmosis later on, but prefer to understand these points right
now. Sometimes I make things too complicated, too.

The key seems to be basic referencing, which is easy to understand, coupled
with anonymous referencing, which is also easy to understand. With closures
and classes, the problem is understanding what is being left behind and why.
What exactly is the syntax doing? It seems the way closures are created is
the manner in which a routine exits. The author left a good trail, with all
the preliminaries in place, but failed to put everything together at the end
to enable whatever visualization. I read
http://www.perldoc.com/perl5.6/pod/perltoot.html. Though quite good, it
still did not complete the picture for me. Any comments would be
appreciated. Thanks
 
M

Matija Papec

X-Ftn-To: David McDivitt

David McDivitt said:
The key seems to be basic referencing, which is easy to understand, coupled
with anonymous referencing, which is also easy to understand. With closures
and classes, the problem is understanding what is being left behind and why.
What exactly is the syntax doing? It seems the way closures are created is
the manner in which a routine exits. The author left a good trail, with all
the preliminaries in place, but failed to put everything together at the end
to enable whatever visualization. I read
http://www.perldoc.com/perl5.6/pod/perltoot.html. Though quite good, it
still did not complete the picture for me. Any comments would be
appreciated. Thanks

Closure is a /subroutine/ which refers to lexical variables declared outside
the subroutine itself.. so Damian defines closures in OO Perl.

What you're missing in your picture?
 
U

Uri Guttman

DM> I am new to Perl going through the book by Deitel, "Perl How to
DM> Program". I went through the first half the book pretty fast and
DM> only did a few of the programming examples to understand. I even
DM> made a good application with what I read this far having four web
DM> pages, CGI functionality, functions, hashes, Perl default
DM> variables, and code optimizations.

get a better book. there is no need for most newbies to use closures.

DM> I seem to be stuck on the conceptual matter of referencing,
DM> closures, and classes. The book is good to the extent it covers
DM> the whole language and represents a good plan for learning the
DM> language. Unfortunately, I have found the book lacking in
DM> description of a few key points. They are glossed over with
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

see, it is a bad book if it does that. go to learn.perl.org for more on
better books (including a good one that is free online).


DM> sentences lacking sufficient detail or are ambiguous. It is as if
DM> the author is impatient to move on. Not only am I learning the
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

another sign of a bad book.

DM> language myself to write production applications, but I am also
DM> leaving behind a methodology for others here to follow. When parts
DM> of the book need clarification I find it for my own benefit, then
DM> create a text document having the problem chapter and section. It
DM> is my hope others can go through the book and read these little
DM> text files for clarification when necessary.

DM> I don't like to assume things, and I don't like to do things just
DM> because the book or so-and-so says so. I have read several
DM> articles on referencing, closures, and classes, but am unable to
DM> understand exactly why it works and what Perl is doing with
DM> these. I could move on in the book then get what I want through
DM> osmosis later on, but prefer to understand these points right
DM> now. Sometimes I make things too complicated, too.

why do you think you need closures? closures are not really related to
references (even though closures are made with anon code refs) in general.


DM> The key seems to be basic referencing, which is easy to
DM> understand, coupled with anonymous referencing, which is also easy
DM> to understand. With closures and classes, the problem is

references don't know if they are 'regular' or 'anonymous', they are
just references. if your book separates them like that, then get a
better book.

DM> understanding what is being left behind and why. What exactly is
DM> the syntax doing? It seems the way closures are created is the
DM> manner in which a routine exits. The author left a good trail,
DM> with all the preliminaries in place, but failed to put everything
DM> together at the end to enable whatever visualization. I read
DM> http://www.perldoc.com/perl5.6/pod/perltoot.html. Though quite
DM> good, it still did not complete the picture for me. Any comments
DM> would be appreciated. Thanks

get a better book. this one sounds awful from only your description.

here are a few to start with. search google in this group for more
recommendations.

learning perl
elements of programming with perl
programming perl


uri
 
C

Charlton Wilbur

UG> get a better book. this one sounds awful from only your
UG> description.

The Deitel & Deitel _C: How to Program_ was a very good book; it's the
one I was taught C from. I've since replaced it with K&R2 (which got
stolen) and with Harbison & Steele, but it was a very good book all
the same.

Their _C++: How to Program_ was disappointing, as was their _Java: How
to Program_. I'm not surprised that the Perl one is horrible, alas.

Charlton
 
D

David McDivitt

Here is what the book says:

*********

Anonymous functions come into existence at runtime. The part of the code in
which an anonymous function is created has it's own lexical context <ok>.
The values of variables created in the same lexical context as an anonymous
function can be used by the anonymous function when it is called later in
the program <ok>. Anonymous functions save the information about the context
in which they were created and execute as if they were still in that
context. The anonymous functions act as "closures" with respect to lexical
variables <taken for granted but OK>.

5 use warnings;
6 use strict;
7
8 print( "The number is square( 5 ).\n" );
9 print( "The number is ${ \square( 5 ) }.\n" );
10
11 sub square
12 {
13 my $x = shift();
14 return $x * $x;
15 }

The number is square( 5 ).
The number is 25.
fig 13.7

An example where this can be useful is when a function returns an anonymous
function reference. The function reference will contain the state
information pertaining for the lexical context in which it was created.
Figure 13.8 demonstrates this concept.

Function "animalInFood"(lines 8-16) returns a reference to an anonymous
function (defined at lines 11 thru 15). Line 10 creates a lexical variable
"$x", which stores the value passed to function "animalInFood" as an
argument. Note that the anonymous function uses the lexical variable "$x" in
line 14. Each time the "animalInFood" function is called, a new "$x" is
created because it is declared with the "my" keyword. When the anonymous
function is created on line 11, the "$x" it refers to is the specific "$x"
that exists at the time the function is created, not the value that "$x"
holds when the anonymous function is called. This association of the
variable "$x" in the closure with the specific instance of "$x", rather than
the name "$x", is known as "deep binding". Only lexical variables provide
deep binding. If we used the "local" keyword on line 10 instead of "my", we
would not have deep binding and the anonymous function returned would not be
a closure.

5 use warnings;
6 use strict;
7
8 sub animalInFood
9 {
10 my $x = shift();
11 return sub #what the hell does return sub mean?
12 { #no description given anywhere
13 my $y = shift();
14 print( "There is a $x in my $y!\n" );
15 };
16 }
17
18 my &$flyInFood = animalInFood( "fly" );
19 my &$frogInFood = animalInFood( "frog" );
20
21 &$flyInFood( "soup" );
22 &$frogInFood( "coffee" );

There is a fly in my soup!
There is a frog in my coffee!
fig 13.8

You can see that "animalInFood returns closures because when we assign
variable "$flyInFood" the closure returned by passing "animalInFood" the
word "fly", then call "animalInFood" again with the value "frog". Each
closure is stored in a reference. These references are used at lines 21 and
22 to invoke each closure. Note that the closure invoked at line 21 prints a
string containing the word "fly", which was passed to the first call to
"animalInFood". Similarly, the closure invoked at line 22 prints a string
containing the word "frog", which was passed to the second call to
"animalInFood".

********************************

I don't know what I'm supposed to get from this. It is not well written in
my opinion and I fail to get the point of even reading it. Closures seem to
be very important however, and understanding closures would seem to help one
understand classes, too. Thanks
 
D

David McDivitt

The book has been OK to present. When things get too complex it breaks down,
and the book seems a recital to someone already knowledgeable. It does give
a good plan. One thing I don't like is the way it talks in ridiculously
simple terms sometimes, as if to an infant, then glosses over crucial stuff
with no descriptive effort at all. Each little thing has one time slice. If
easy, the one thing is spread monotonously across the entire timeslice. If
difficult, the one thing is crammed into the same size timeslice.

I took two Java classes and in the second Deitel, "Java How to Program" was
used. For the most part it was OK. The entire book was also on the
accompanying CD, as well as program and runtime examples I could just click
on.

I was hoping to get the same thing this time; CD version of the book, etc.
Boy am I disappointed.
 
E

Eric Schwartz

David McDivitt said:
5 use warnings;
6 use strict;

Yaay for these, anyway! Too many books omit them.
8 sub animalInFood
9 {
10 my $x = shift();

Here, x is a lexical. Don't obsess about the fact that it exists in a sub.

11 return sub #what the hell does return sub mean?
12 { #no description given anywhere

I assume you know what return does (returns a value or values from a
function) and what sub does (defines a subroutine). This combines the
two-- defines a subroutine, and returns a reference to it.
13 my $y = shift();

The subroutine being created has one parameter.
14 print( "There is a $x in my $y!\n" );

Here's where "closure" comes into it. Notice that this anonymous
subroutine refers to $x. Since $x is a lexical variable outside the
scope of this subroutine, its value is captured /as of the time the
sub is defined/, and that value will be used whenever the sub is
returned.
15 };
16 }
17
18 my &$flyInFood = animalInFood( "fly" );

The & is unnecessary here. animalInFood is returning a reference to
an anonymous sub that takes one argument. In that sub, $x is set to
"fly", since that's the value it had at the time the sub was defined,
and $y will take whatever value you give it when you call the sub.
19 my &$frogInFood = animalInFood( "frog" );

Likewise, remove the &. Here, animalInFood returns a reference to a
subroutine in which takes one argument, and where $x is set to "frog".
21 &$flyInFood( "soup" );
22 &$frogInFood( "coffee" );

Here, you dereference the subroutines you created by calling
animalInFood above, and pass them arguments. They retain the value of
$x from when they were defined, and take $y from the arguments you
pass to them.

You can also call these sub refs as:

$flyInFood->("soup")
$frogInFood->("coffee")
I don't know what I'm supposed to get from this. It is not well written in
my opinion and I fail to get the point of even reading it. Closures seem to
be very important however, and understanding closures would seem to help one
understand classes, too. Thanks

99% of the Perl programs I write don't need or use closures. I'd say
100%, except that I'll bet I've done it once or twice, and just forgot
about it. I have no idea whether my experience will reflect yours,
however.

It's confusing and hard to follow when things are upside-down.
Why not?
Also, please do not top-post.

If you read the Posting Guidelines, which are posted here regularly,
you'll be more likely to get better responses than mine, I'm sure.

-=Eric
 
B

Bob Walton

David McDivitt wrote:

....

5 use warnings;
6 use strict;
7
8 sub animalInFood
9 {
10 my $x = shift();
11 return sub #what the hell does return sub mean?
12 { #no description given anywhere


The "return sub {...}" is returning a code reference to the anonymous
sub consisting of the code between the braces (see perldoc -f sub to see
what the sub function does). Bear in mind that when there is no
semicolon or ending brace, the Perl expression isn't over yet -- it
continues on subsequent lines. In this case, that anonymous sub is a
closure because it uses $x, a lexical variable which was already defined
in the scope of the sub at the time the sub was defined. You will note
that if you call the returned code reference, it remembers the value of
the in-scope lexical at the time the sub was defined. There is no magic
to this, and actually, it barely warrants the special name "closure"
(which name, as far as I can tell, might as well be any made-up name, as
the ordinary concept of "closure" seems to bear no relation to this).
It is simply a matter of the normal behavior of scoped lexical
variables. Each time "animalInFood" is called, another anonymous code
reference consisting of a sub with $x already in its scope with the
value is has at the moment is created. When that code reference is
executed later, it remembers its $x. That's all there is to it. For
fun, try writing closures which modify their already-in-scope variables.

13 my $y = shift();
14 print( "There is a $x in my $y!\n" );
15 };
16 }
17
18 my &$flyInFood = animalInFood( "fly" );
19 my &$frogInFood = animalInFood( "frog" );
20
21 &$flyInFood( "soup" );
22 &$frogInFood( "coffee" );

There is a fly in my soup!
There is a frog in my coffee!
fig 13.8

You can see that "animalInFood returns closures because when we assign
variable "$flyInFood" the closure returned by passing "animalInFood" the
word "fly", then call "animalInFood" again with the value "frog". Each
closure is stored in a reference. These references are used at lines 21 and
22 to invoke each closure. Note that the closure invoked at line 21 prints a
string containing the word "fly", which was passed to the first call to
"animalInFood". Similarly, the closure invoked at line 22 prints a string
containing the word "frog", which was passed to the second call to
"animalInFood".

********************************

I don't know what I'm supposed to get from this. It is not well written in
my opinion and I fail to get the point of even reading it. Closures seem to
be very important however, and understanding closures would seem to help one
understand classes, too. Thanks


Well, it seems fairly clear to me, but I do think it would be better to
describe the phenomenon as simply the expected behavior of scoped
lexical variables, just exactly like what happens in any other scope. I
don't know how important they are -- I guess they can be pretty
important for generating obfuscated code, maybe. And they do let you
create truly private variables which absolutely nothing can touch other
than your own methods when you create modules. But that probably isn't
very important either (hey, someone can just modify the code of your
module if they really want to, so what did it really gain? Oh, yeah, it
obfuscated it to the point where they couldn't understand it anyway, so
maybe it did keep your module private :).).


....
 
E

Eric J. Roode

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

David,

I would *strongly* recommend Damian Conway's excellent book, _Object
Oriented Perl_. It covers references, closures, objects, and classes in
great detail, and is very readable and clear, imho. Well worth the cover
price.

In a nutshell: A reference is a scalar value that holds information
about a scalar, array, hash, subroutine, filehandle, etc. It is sort of
analogous to a pointer in C or Pascal (if you know C or Pascal), except
that it holds more information than just a pointer. References are _very_
useful, and understanding them is key to becoming an intermediate to
advanced Perl programmer.

A closure is more subtle. It is a reference to an anonymous subroutine
(that is, a subroutine that has been defined with a naked "sub" declaration
and no name), and which refers to one or more lexical ("my") variables that
are declared outside the scope of the subroutine definition. The clever
and magical thing that happens is that the closure "remembers" the values
of those lexical variables, even if they change later. More specifically,
at the time the anonymous subroutine is stored, it gets a private copy of
the lexical variables it references outside its scope. This is rather
useful in some circumstances.

- --
Eric
$_ = reverse sort $ /. r , qw p ekca lre uJ reh
ts p , map $ _. $ " , qw e p h tona e and print

-----BEGIN PGP SIGNATURE-----
Version: PGPfreeware 7.0.3 for non-commercial use <http://www.pgp.com>

iQA/AwUBP2pdNGPeouIeTNHoEQKT8QCgmqPbjHO2OVRb/2oX1vHc1GEiP2AAoI0R
9gItgTctedFY6T9rsourDj2o
=RGc2
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top