Subject: | Question about overload |
Here is an example including a lot of code only to accept the overload
problem:
I have a subroutine named "print_string", 1 parameter, a string.
Now this subroutine is called with an overloaded object "MyString".
Without Params::Validate there is no problem, I accept SCALAR.
Otherwise I have to accept OBJECT to but not every object.
What should I do?
-----------------------------------------------------------
package MyString;
use strict;
use warnings;
use overload q{""} => 'stringify';
sub new {
my ($class, $string) = @_;
return bless \$string, $class;
}
sub stringify {
my $self = shift;
return ${$self};
}
package main;
use strict;
use warnings;
use Params::Validate qw(:all);
use Carp qw(confess);
sub print_string {
my ($string) = validate_pos(
@_,
{
type => SCALAR | OBJECT,
callbacks => {
stringify => sub {
UNIVERSAL::can( shift, q{(""} )
or confess q{Only objects with overloaded ""
are allowed};
$_[0] = q{} . $_[0];
1;
}
},
},
);
print $string, "\n";
}
print_string(MyString->new('This is a string!'));
print_string(bless {}, __PACKAGE__);