---
#!/usr/bin/perl
use strict;
use pkg;
print pkg::connect();
---
This is a question someone asked me, that I didn't really have the answer, other than, "this is the way I've always done it." The question is: What is the difference between using pkg::connect() and pkg->connect()
So in the above example the pkg::connect() would just call connect() in pkg scope, but pkg->connect() would call connect() of the pkg object? I'm not totally clear on this and I guess after all these years of not questioning DBI->connect(), I'm also curious as to why we don't just do DBI::connect()
pkg->connect() on the other hand calls the connect-method as a pseudo-object (at least I believe...) of pkg-class, working just as $pkg->connect() would, possibly returning the object (like DBI does for initialization).
In perls OO-style, the methods are actually just functions which expect the object they belong to as the first argument. if you call a subroutine in a different namespace using pkg->subr(), the class will be passed as the first argument (for object initialization), if you call it with pkg::subr(), it won't, which is why DBI::connect() does not work with the same arguments as DBI->connect(), while DBI::connect('DBI', $dsn...) should.
here's a test to show the difference:
#!/usr/bin/perl
package main;
test1::test(); #prints "no first arg"
test1->test(); #prints "first arg: test1"
package test1;
sub test {
print 'first arg: ' . $_[0] . "\n";
}
as for the way DBI does it: I think the DBI-way is fine, allthough it might be more obvious to create the object with something like
my $obj = pkg->new();
before telling it to connect with
$obj->connect();
That'd keep the whole confusion out of the way. DBI takes ->connect calls, builds its object within that sub routine and returns it, that's why you use DBI->connect and work with $dbh->prepare after the initial connect. DBI doesn't have a new-routine so ->connect is the only way available.
v7r: good question!
i never thought about it much before you asked.
jh: i like your answers.
i think the simplistic answer to the original question is that :: indicates a class method and -> indicates an object method but that doesn't really answer the when or why question.
D: the returned object is usually a handle or reference to the object.
in most cases the handle is a reference to a hash.
Granted, I'm not a Perl expert, but I hope to be one day. With all of your help, I might actually get there :) I'll try to see how it works if I evaluate the first parameter.
Thank you for all your comments.
[edited by: phranque at 12:12 am (utc) on Dec. 10, 2008]
[edit reason] fixed smileys [/edit]