in reply to Tie Me Up, Tie Me Down

I have two API changes to request and a request to consider prior work in this space.

Common validation code in Regexp::Common and Params::Validate already pepper my code. Is there a chance you could draw on these modules when building your common library of constraints? I'd like to be able to use similar validation facing code without having to keep too many variations of how to do this in my head.

Accept more than a single code reference for validation. Consider { 'Is an integer' => sub { ... }, 'Is prime' => sub { ... } } as a list of named conditions that must be fulfilled. I could have put all that into my single passed in function but its also nice to just document the properties that will be checked by name and leave them all separate.

I'd like some sugar for tieing multiple variables. How about presenting a tie-or-die function so I can constrain multiple variables without lots of effort?

constrain_this( \ ( my $x ) => { 'Property 1' => sub { ... }, 'Property 2' => sub { ... }, }, \ ( my $y ) => { 'Property 1' => ...

Replies are listed 'Best First'.
Re^2: Tie Me Up, Tie Me Down
by Zaxo (Archbishop) on Jan 16, 2005 at 20:27 UTC

    Regexp::Common is a very good partner for this tied technique - I had it in mind when I wrote Tie::Constrained. Here's an example of a subclass, Tie::Constrained::URI, where a tied variable is by default restricted to be a well-formed URI.

    package Tie::Constrained::URI; use vars qw/@ISA/; use Regexp::Common 'URI'; use Tie::Constrained; @ISA = qw/Tie::Constrained/; sub validate { $_[0] =~ /^$RE{URI}$/ } 1; __DATA__ Usage: use Tie::Constrained::URI; my $href_ctl = tie my $href, 'Tie::Constrained::URI'; tie my $ftpref, Tie::Constrained::URI => sub { $_[0] =~ /^$RE{URI}{FTP}$/ }; $href_ctl can be used to change the test on the fly. $href_ctl->{'test'} = sub { $_[0] =~ /^$RE{URI}{HTTP}$/ } if $href =~ /^$RE{URI}{HTTP}$/;

    As it stands, I think that Params::Validate compatibility is for the future, but it's a very good idea. I'll probably need to rename my validate class method again.

    Many of the simpler things Params::Validate does for objects can be imitated with scalar Tie::Constrained as it is:

    tie my $obj, Tie::Constrained => sub { !$_[0] or $_[0]->isa('My::Frobnicator'); };
    The first term is so that $obj can be undefined to break circular references.

    Thank you much for the suggestions, I'll take them very seriously.

    After Compline,
    Zaxo