SPUG: Question: scoping
Ronald J Kimball
rjk-spug at tamias.net
Mon Sep 15 14:42:25 PDT 2008
On Mon, Sep 15, 2008 at 01:11:02PM -0800, Christopher Howard wrote:
> When I run this, I get "Can't call method "value" without a package or
> object reference at ./main.pl line 13." from the interpreter. I was a
> bit confused, so I put constructor and de-constructor registration code
> into MyClass, to track was was happening to the objects.
>
> From what I can tell, the objects are getting destroyed before they
> leave the scope of the first for loop. This leaves me still confused,
> because I declared @obj outside of the scopes of the for loops.
Works for me. I suspect the problem is that MyClass's new method is not
actually returning the blessed reference.
> Obviously I could solve the immediate problem by putting them both in
> the same for loop. But what I really want is to understand why the
> objects are going out of scope before I think they should be.
So, did you actually try that yet...? :)
Ronald
P.S. Here's the code and I ran, and the output:
#!/usr/bin/env perl
use strict;
use warnings;
my @obj;
for(my $i = 0; $i<10; $i++) {
$obj[$i] = new MyClass;
}
for(my $i = 0; $i<10; $i++) {
$obj[$i]->value("Test Value.");
}
1;
package MyClass;
sub new {
return bless {}, shift;
}
sub value {
print "@_\n";
}
__END__
MyClass=HASH(0x811f27c) Test Value.
MyClass=HASH(0x811fa50) Test Value.
MyClass=HASH(0x814496c) Test Value.
MyClass=HASH(0x8144960) Test Value.
MyClass=HASH(0x8144024) Test Value.
MyClass=HASH(0x814400c) Test Value.
MyClass=HASH(0x814cfd8) Test Value.
MyClass=HASH(0x814cfc0) Test Value.
MyClass=HASH(0x814cfa8) Test Value.
MyClass=HASH(0x814cf90) Test Value.
More information about the spug-list
mailing list