#!/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 in 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 message { croak "Package ".ref($x)." doesn't overload stringification: $@" } else { die $@ } } else { ref($x) and warnings::warnif("Argument list contains references/objects"); return "$x" } } #### OnlyAString: 111 ICanStringify: 222 Package OnlyANumber doesn't overload stringification: Operation """": no method found, argument in overloaded package OnlyANumber at ...