Click here to get back home

Side effects of overloading quotes ""

 HomeNewsGroups | Search | About
 comp.lang.perl.modules    Post an article   get this group's latest topics as an RSS feed add this group's latest topics to your My MSN content add this group's latest topics to your My Yahoo content
Subject Author Date
Side effects of overloading quotes "" Koszalek Opalek 11-28-2007
Posted by Koszalek Opalek on November 28, 2007, 3:07 pm
Please log in for more thread options
Hello,

I overloaded the quotes '""' in my class by using
use overload ('""' => \&getDesc);

I was hoping it will allow me to write
print ("Hello from object $obj.\n");
instead of
print ("Hello from object " . $obj->getDesc() . ".\n");

Well, it works that way but there are side effects that break my class
completely.


Problem 1)

Before overloading, statement
if ($obj)
is true, if $obj is a reference to any object of class Obj.
If the reference is undef, $obj is false.
After overloading "", $obj is also false if getDesc() happens to
return an empty string! That's not what I wanted. If I did, I could
use
if ("$obj")


Problem 2)

Before overloading I could compare object references
if ($obj1 == $obj2)
and check if they point to the same location/object. I can no
longer do that once the '""' operator has been overloaded.

Operation "==": no method found,
left argument in overloaded package Obj,
right argument in overloaded package Obj at ./a.pl
line 38.

I can use eq instead of == if I also add falllback => 1 to the
overload pragma but that string-compares $obj1->dummy()
with $obj2->dummy() instead of object references. Again, if
I wanted to compare the string representation I could do
if ("$obj1" eq "$obj2")

Am I doing sth wrong or miss the point completely? Or is this
overload module broken?

I enclose a short listing that demonstrates my point.
Uncomment one of the #use clauses to see how it breaks(?)
things. Any help will be appreciated.

#!/usr/bin/perl
use strict;
use warnings;

{
package Obj;
#use overload ('""' => \&getDesc);
#use overload ('""' => \&getDesc, fallback => 1);

sub new ()
{
my $class = shift;
my $self = {};

bless $self, $class;

}

sub getDesc ()
{
return "";

};
};

my $obj1 = Obj->new();
my $obj2 = Obj->new();

### PROBLEM 1 ###
if ($obj1) {
print "true\n";
} else {

print "false\n";

};

### PROBLEM 2 ###
if ($obj1 == $obj2) {
print "same references\n";
} else {

print "different references\n";

};

__END__


I originally posted it to comp. lang perl. misc but maybe *.modules
is better suited for this.

Koszalek

Similar ThreadsPosted
WWW::Mechanize single quotes around url January 12, 2007, 12:54 am
Test::Harness overloading of PERL5LIB February 7, 2006, 3:46 pm

Our other projects:

Art Dolls, Fairies and Mermaids - Sunnyfaces.net

Roy's Linux, Programming and Search Engines messages

1-Script XML SitemapXML Sitemap