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.
>
> 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]
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
>
> The $refToOperator is the problem bit. Can that be done, or is there a
> better way to solve the problem?
>
> Thanks,
> Tim Bowden
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
My Aphorisms - http://www.shlomifish.org/humour.html
Deletionists delete Wikipedia articles that they consider lame.
Chuck Norris deletes deletionists whom he considers lame.
Please reply to list if it's a mailing list post - http://shlom.in/reply .
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/