Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2015-07-03 00:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (47 votes), past polls