Subject: | Coerce to/from native types via Param::Coerce::* |
This may be an off-the-wall request... Feel free to revise/reject.
I always see CPAN code that takes some variant of
filename/filehandle/stringref/default_to_STDIN. The param checking is
complicated and doesn't always cover all cases. It would be cool if
this idiomatic mess could be simplified into a coercion to a filehandle.
[ This request is related to RT #18212, "Patch that add supports for
Perl types": http://rt.cpan.org/Ticket/Display.html?id=18212 ]
I'd love to see scalarref to filehandle coercion done like this:
use Params::Coerce::Filehandle;
use Params::Coerce _FH => Filehandle;
sub read {
my $fh = _FH($_[0]);
...
}
and implemented as something like
package Params::Coerce::Filehandle;
use IO::Scalar;
sub __from_SCALAR {
my $str_ref = shift;
return IO::String->new($$str_ref);
}
sub __to_SCALAR {
my $self = shift;
local $/ = undef;
my $str = <$self>;
return \$str;
}
(Caveat: that only does read filehandles. Not sure how to support write
filehandles. Also not sure how to support filename strings.)
This could be supported in Params::Coerce by adding code to _resolve() like:
if ("Param::Coerce::$want"->can("__from_$have")) {
return _hint($key, "^Param::Coerce::${want}::__from_$have");
}
if ("Param::Coerce::$have"->can("__as_$want")) {
return _hint($key, "^Param::Coerce::${have}::__as_$want");
}
This could be used similarly for turning an url string into a URI
instance perhaps. then third parties could add Param::Coerce::*
packages to CPAN to add coercion functionality to existing modules.