[Chicago-talk] blessing horrors

Jim Thomason jthomasoniii at yahoo.com
Wed Apr 14 20:23:28 CDT 2004

Here's a stupid perl trick I learned today. Quick,
think fast. What does this code output:


my $object = bless {}, 'foo';

print ref($object), "\n";

sub set_some_value {
        $main::foo::bar::baz = 1;

Now, other than Randal, who got it right?

I'm sure most of you are now scratching your heads and
saying, "What's he talking about? It prints out
'foo'." But, alas, it does not. In this case, it
prints out 'main::foo'. 

That's right! $object here actually an instance of
'main::foo', not 'foo'. Now, this isn't as dire as you
may immediately think - 'foo', 'main::foo', and
'::foo' are all functionally equivalent. So it's
(usually) not going to break your code or anything.

It bit me in the ass today because I use a conf file
that defines default values for various attributes in
various classes. So my conf file has a line in it as

define package Basset::DB

which I later discovered bombed miserably when I tried
to stick default values into my object that had
managed to become part of the main::Basset::DB package

Solution? I added a new method to my framework called
'class' that does nothing but return the class of an
object, with the (main)?:: stripped off the front.
Problem solved.

The reason? That I'm not quite clear on. I found this
article in Google's Groups http://tinyurl.com/39tma
that sheds a lot of light on the situation, but
doesn't completely resolve it to my satisfaction.
Basically, if you reference something in 'main::foo'
before something in 'foo', you're stuck with objects
ending up blessed into 'main::foo'. But, as you can
see from my funny little example above, that first
occurence apparently happens at compile time, not
runtime. So you can have wacky things happen where
your objects return different values from ref
depending upon where in your code you use a main::foo

Fun stuff.


Do you Yahoo!?
Yahoo! Tax Center - File online by April 15th

More information about the Chicago-talk mailing list