Hi everyone,
First of all, apologies for my extremely late reply, I'm working on this in my free time and I haven't had a chance to get back to it until now.
So below is the logic I am now using, and it seems to work: the function "strify" takes a value, produces the warnings / errors that I wanted to provide for user-friendliness, and otherwise should act like normal Perl stringification. If I wasn't providing those custom warning and error messages, the whole thing could be simplified quite a bit, that's something I'll consider for the next version. You can see the code (with detailed comments) in my module here. In researching a solution I ended up writing a bunch of test classes and test cases.
#!/usr/bin/perl use strict; use warnings; { package OnlyAString; use overload fallback=>0, '""'=>sub { ${shift()} } } { package ICanStringify; use overload fallback=>undef, '0+'=>sub { ${shift()} } } { package OnlyANumber; use overload fallback=>0, '0+'=>sub { ${shift()} } } print " OnlyAString: ",strify(bless \do {my $x=111}, 'OnlyAString' ) +,"\n"; print "ICanStringify: ",strify(bless \do {my $x=222}, 'ICanStringify') +,"\n"; print " OnlyANumber: ",strify(bless \do {my $x=333}, 'OnlyANumber' ) +,"\n"; use Scalar::Util 'blessed'; use overload (); use Carp; sub strify { my ($x) = @_; if (!defined $x) { warnings::warnif('uninitialized','Use of uninitialized value i +n argument list'); return "" } elsif (blessed($x) && overload::Overloaded($x)) { if (overload::Method($x,'""')) # we can assume stringify will + work { return "$x" } elsif (defined(my $rv = eval { "$x" })) { return $rv } elsif ($@=~/\bno method found\b/) # throw custom error messag +e { croak "Package ".ref($x)." doesn't overload stringificat +ion: $@" } else { die $@ } } else { ref($x) and warnings::warnif("Argument list contains reference +s/objects"); return "$x" } }
Output:
OnlyAString: 111 ICanStringify: 222 Package OnlyANumber doesn't overload stringification: Operation """": +no method found, argument in overloaded package OnlyANumber at ...
Thanks and Regards,
-- Hauke D
In reply to Re: Can I ask Perl if an object will stringify?
by haukex
in thread Can I ask Perl if an object will stringify?
by haukex
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |