Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

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

Comment on Re: dualvar for a reference-string combination
Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://914987]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2015-10-07 00:44 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (166 votes), past polls