Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: dualvar for a reference-string combination

by Corion (Pope)
on Jul 17, 2011 at 18:37 UTC ( #914987=note: print w/replies, xml ) Need Help??

in reply to dualvar for a reference-string combination

Can you maybe do with just using overload? Then you can control what happens when your object is used as a string, used as a number and other things... Your example would fit this usage:

package My::DateObject; use DateTime; use vars '$AUTOLOAD'; use Carp qw(croak); use overload q{""} => 'as_string'; sub new { my ($class, %args) = @_; my $self = { dt => DateTime->now(), %args, }; bless $self => $class; }; sub as_string { $_[0]->{ dt }->ymd("-"); }; sub DESTROY {}; # we have AUTOLOAD sub AUTOLOAD { # blindly delegate to $self->{dt} $AUTOLOAD =~ /::(\w+)$/ or croak "Malformed method '$AUTOLOAD'"; my $method = $1; $_[0]->{dt}->$method(@_); }; package main; my $do = My::DateObject->new(); print "As string: $do\n"; print "As object: ", $do->mdy("/"),"\n";

Update: Fixed lots of typos in the untested code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://914987]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2018-01-24 01:07 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (254 votes). Check out past polls.