On Fri, 2010-04-16 at 12:51 +0300, Shlomi Fish wrote:
> Hi Tim,
> 
> On Friday 16 Apr 2010 12:06:31 Tim Bowden wrote:
> > I've got a nested hash data structure, and I want to create tests for
> > many of the attributes within that data structure, but I'm not sure of
> > the best way to do that.
> > 
> > Example:
> > 
> > my $dataStructure = {'GroupA'=>{
> >     'element1'=>{
> >       'attrib1'=>'someValue', 'attrib2'=>'otherValue'},
> >     'element2'=>{
> >       'attrib1'=>'someValue', 'attrib2'=>'otherValue'},
> >   },
> >   'GroupB'=>{
> >     'element1'=>{
> >       'attrib1'=>'someValue', 'attrib2'=>'otherValue'},
> >     'element2'=>{
> >       'attrib1'=>'someValue', 'attrib2'=>'otherValue'},
> >   },
> > };
> > 
> > It doesn't take too many 'Groups' or 'elements' before testing for
> > sensible 'attrib' values becomes very unwieldy, particularly as each
> > 'Group' will have slightly different 'elements'.  Rather than creating
> > some huge difficult to maintain 'if elsif' tree to test relevant
> > attributes, I was hoping there was some way I could create a generic if
> > statement, and put the tests within the data structure by adding
> > something like:
> > 
> > 'test_operator' => '=', 'test_value' => 'somevalue'
> 
> test_operator should likely be "==" or "eq" and not "=", as the latter is 
> assignment.

Yes.  Slip of the keyboard in my hast.  Doh.

> 
> > 
> > at the 'attrib' level of the data structure.  Then the if statement
> > would look something like..
> > 
> > if ($refToAttrib $refToOperator $refToTestValue){...
> 
> That syntax won't work in Perl. However, you can use a dispatch table and 
> wrap 
> the operator in a subroutine:
> 
> [code]
> my %ops=
> (
>       "==" => sub { my ($attrib, $value) = @_; return $attrib == $value; },
>       ">" => sub { my ($attrib, $value) = @_; return $attrib > $value; },
> );
> [/code]
> 

That looks like a reasonable approach.

> If you're using Test::More, you can also look at its cmp_ok which does 
> something along these lines.
> 
> [bad idea] # Just for enlightenment
> Perl 5 is a dynamic language and you can pull similar stunts with the string 
> eval "". However, you always risk code injection that way, and in this case 
> it's not really necessary.
> [/bad idea]
> 
> Regards,
> 
>       Shlomi Fish

Thanks,

Tim Bowden


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to