The short answer is that you can't do this using eval the way you want to because Perl needs to know at compile time whether a variable you're using is a global or a lexical, so it doesn't make sense to declare lexical variables in eval'd code and then use them in non-eval'd code in the same block. But I don't think you need anything so drastic.
I would start at the most basic level. It sounds like what you're trying to do can be described simply as "assign some lexical variables to values passed in through a hash, and make sure they're defined." The simplest way to do the assignment part is
So far so good. But we also need to insure that a) the parameters are all there, b) there are no extraneous parameters, and c) they all have defined values. This we can abstract into a subroutine like this:my ($self, %values) = @_; # we're being passed a hash so let's treat +it like a hash my ($tree, $messageNum, $messageText) = @values{qw/tree messageNum mes +sageText/};
and we can call it like this:sub validateParams { my ($data, @paramNames) = @_; die "first argument to validateParams must be a hash" unless ref +$data eq 'HASH'; my $expect_count = @paramNames; my $actual_count = keys %$data; die "incorrect number of parameters - expected $expect_count, got + $actual_count" unless $expect_count == $actual_count; for my $name (@paramNames) { die "parameter $name missing or undefined" unless defined $da +ta->{$name}; } }
I put it in an enclosing block like that so that each subroutine can have its private list of required parameter names set up in advance.{ my @paramNames = qw/tree messageNum messageText/; sub new { my ($self, %values) = @_; validateParams(\%values, @paramNames); my ($tree, $messageNum, $messageText) = @values{@paramNames}; } }
There are also some modules on CPAN for this such as Params::Validate.
In reply to Re^3: Usage of 'my' in 'eval'
by Errto
in thread Usage of 'my' in 'eval'
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |