develooper Front page | perl.beginners | Postings from March 2002

anonymous subroutine problem

Thread Next
From:
Paul Tremblay
Date:
March 27, 2002 18:47
Subject:
anonymous subroutine problem
Message ID:
20020327214756.D26666@localhost.localdomain
I am coppying the code below directly from *Object Oriented
Perl* by Conway. (Error message is below.)


package CD::Music;
#use strict; # turn this off for testing purposes

{

	my $_count = 0;
	sub get_count		{$_count}
	my $_incr_count = sub {++$_count};#create an anonymous subroutine
	$_incr_count->();# it works if I call it here

sub new{
	$_incr_count->();#call the anonymous subroutine
#this line above causes the error below
	

#Isn't this where the anonymous subroutine should go?
		#my $_incr_count = sub {++$_count};

	
	my ($class) = @_; 
	bless {
			_name	=>	$_[1], 	#second value passed to subroutine
			_artist	=>	$_[2],	#third value passed to subroutine
			_publisher =>	$_[3],	#and so on
			_ISBN	=>	$_[4],
			_tracks	=>	$_[5],
			_room	=>	$_[6],
			_shelf	=>	$_[7],
			_rating	=>	$_[8],
		}, $class;
}
}

I am getting this error message:

/home/paul/bin/test16.pl
Use of uninitialized value in subroutine entry at /home/paul/bin/test16.pl 
line 29.
Undefined subroutine &main:: called at /home/paul/bin/test16.pl line 29.

I am nearly positive that this error message results because the 
reference to the anonymous subroutine expires once I start the 
subroutine new.

Could a more experienced user confirm this?

I believe that the annonymous subroutine (and the other code
that initializes the counter) should go in the new subroutine
block. The idea is make sure you can't access the subroutine
directly. This happens  as long as I make an anonymous
subroutine--no matter where I put it.

Thanks! 

PS: Typos in computer books can really cause you to lose your
mind. You keep thinking that you typed something wrong!

-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About