SPUG: Question: scoping
Christopher Howard
choward at indicium.us
Mon Sep 15 14:11:02 PDT 2008
Yello. I was trying to figure out a certain concept, so I was creating
a tiny test program. Then I ran into something that didn't make sense
to me. Here's the code:
#!/usr/bin/env perl
use strict;
use warnings;
use MyClass;
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;
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.
Is there some nuance of Perl syntax that I'm not understanding here?
Any insight would be appreciated.
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.
More information about the spug-list
mailing list