Subject: | How to specify optional objects that might be undef (and still use isa) |
I could be missing something, but this need comes up all the time in
code I'm working on: I have a method that needs to take several optional
parameters, but if some of the args exist I need them to be a certain
class of objects. This is pretty simple on the surface:
validate(@_, {
date => { isa => 'DateTime', optional => 1},
bar => { isa => 'Bar::Class', optional => 1},
});
But this doesn't work if the optional args are undef. I could do:
validate(@_, {
date => { type => UNDEF | OBJECT, optional => 1},
bar => { type => UNDEF | OBJECT, optional => 1},
});
But then if I combine that with isa() it still complains that it's not a
DateTime, but an "undef".
I think this is a pretty common pattern to use especially if your
arguments are coming from some other function. Something like this:
foo(date => next_date(), bar => 1);
Now if I want to validate that date is a DateTime if it's passed, then I
need to do something like this instead:
my %foo_args = (bar => 1);
my $date = next_date();
$foo_args{date} = $date if $date;
foo(%foo_args);
Which is way more verbose and clumsy.
So is there a way to do what I want without having to write my own
callback everytime I want to repeat this pattern? If not, are you open
to some sort of feature to make this work?