http://www.perlmonks.org?node_id=1049179


in reply to checking values of variables

So you have really a hash to start with. No point of doing this long list of assignments if the hash is not valid and complete. I therefore come back to the solution I first gave here Re^2: checking values of variables as an answer to toolic's post, just adapting it to the hashref at hand:

for (qw / server database user password ... initversion /) { help() and last unless (defined $cfg->params($_) and $cfg->params +($_));

Although, to tell the truth, my suggestion was just to give a minimal solution. In real life, I would first create an array of the mandatory parameters, and check against that array, rather than a hard coded list. Something like this:

my @mandatory_params = qw / server database user password ... initvers +ion /; for (@mandatory_params) { help() and last unless (defined $cfg->params($_) and $cfg->params +($_)); }

The point of doing that is that the list of parameters is likely to be useful elsewhere, storing it into an array enables to have it defined in one single place. If you need to change it, there is only one place where it needs to be changed.

And, BTW, I do not know what the rest of your program does, but I would most probably not do a long list of assignments of scalar variables with the values of the cfg->param hash; in this case, this is almost like hard coding things than need not be hard coded. Copy the hash ref values into a simple hash, take a simple reference to it, do what you need to gain an access that is easier to understand in your eyes, but don't store all these values into individual scalars, you are losing flexibility and maintainability.

Update: I had not seen davido's answer when I started to make mine, but I think we agree on the basic issues, even though our solutions might not be exactly be the same.

Replies are listed 'Best First'.
Re^2: checking values of variables
by fionbarr (Friar) on Aug 13, 2013 at 12:21 UTC
    this question garnered a fair amount of interest and I appreciate the replies.

      this question garnered a fair amount of interest and I appreciate the replies.

      In what way (what did you decide)?

        I decided to stay with what I have (because the scalar variables are used all over the program and I didn't want to do a great deal of editing). However, next time I have this situation I will most likely use:
        for (qw / server database user password ... initversion /) { help() and last unless (defined $cfg->params($_) and $cfg->params +($_));
        and use $cfg->params(server) instead of $server Thanks to all (Perl Monks is fantastic!)