Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Initial Variables

by Angel (Friar)
on Nov 25, 2002 at 18:15 UTC ( [id://215685]=perlquestion: print w/replies, xml ) Need Help??

Angel has asked for the wisdom of the Perl Monks concerning the following question:

I read many of the OO posts and seem to have missed passing an inital array on the new() function.

http://www.perlmonks.com/index.pl?node=perlman%3Aperlbot has passing the values/scalars as a hash. But not as an array.

What I am trying to do is pass a db handle to an object on creation so that the methods inside can use if for talking to a database.
#example: sub foo ( $self = shift; my $dbh = $self->{$dbh}; $dbh->do{ DELETE FROM EXAMPLE } }

Replies are listed 'Best First'.
Re: Initial Variables
by tadman (Prior) on Nov 25, 2002 at 18:38 UTC
    I find it's easy to make a method like that as long as you're importing hash-style parameters. For example:
    sub new { my $class = shift; my $self = { @_ }; return bless($self, $class); } # ... my $test = Foo->new(handle => $dbh); my $handle = $test->{handle};
    If you're paranoid about what kind of data someone's going to pass in, you can always filter it.
    my @imports = qw [ foo bar ]; sub new { my ($class, %params) = @_; my %self; @self{@imports} = @params{@imports}; return bless(\%self, $class); }
    This will restrict parameters to those in the import list. You could extend this to produce errors, of course.
Re: Initial Variables
by thinker (Parson) on Nov 25, 2002 at 18:33 UTC
    Hi Angel,

    have you considered passing the db handle in as a key => value pair, like
    my $foo=new foo(handle=>$dbh, bar=>"baz", ...);

    then you can assign it to a hash in new(), as in the example you gave.

    Of course, really that is just passing it in as an array (or list), but you don't have to think of it that way. :-)

    Hope this helps

    thinker

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2024-04-24 00:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found