Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^3: Usage of 'my' in 'eval'

by Errto (Vicar)
on Jan 06, 2006 at 15:51 UTC ( [id://521507]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Usage of 'my' in 'eval'
in thread Usage of 'my' in 'eval'

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

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/};
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:
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}; } }
and we can call it like this:
{ my @paramNames = qw/tree messageNum messageText/; sub new { my ($self, %values) = @_; validateParams(\%values, @paramNames); my ($tree, $messageNum, $messageText) = @values{@paramNames}; } }
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.

There are also some modules on CPAN for this such as Params::Validate.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://521507]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-19 13:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found