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


in reply to Re: Would someone mind helping me understand this Perl OO code?
in thread Would someone mind helping me understand this Perl OO code?

Right. Which is what I meant by the 'one off' error - since $pkg is the first variable in the @_ argument list, it would mistakenly get $main::ip assigned to $Node::pkg, right? So is the code wrong? Like I said, it seems to work though.

Replies are listed 'Best First'.
Re^3: Would someone mind helping me understand this Perl OO code?
by almut (Canon) on Dec 22, 2009 at 16:04 UTC

    Node->new(...) implicitly passes the package name (Node) as the first argument to the constructor...  (so you have 4 args in the right slots, and everything is fine)

      I'm sure this behavior is documented somewhere, but didn't see it. Do you know where it can be found?

      Since new isn't a reserved word, how does perl know to pass the package name implicitly into that method in the first place? I could have just as badlyeasily named the constructor 'bargle'. Is the package name passed implicitly on every method call? Or just the one where the object is blessed?
        Do you know where it can be found?

        ...for example in perltoot (search for "Method Call" (case-sensitively)).

        In perlboot, an intro to OO in Perl, it is discussed in The extra parameter of method invocation.

        Update: To answer your updated question, the package name or blessed object are passed in a method invocation whenever you use the The Arrow Operator to invoke a package method. So Node->new() will pass "Node" and new(), Node::new() or $code_ref->() would not.

        It's the first thing perlobj says about methods

        A Method is Simply a Subroutine

        Unlike say C++, Perl doesn't provide any special syntax for method definition. (It does provide a little syntax for method invocation though. More on that later.) A method expects its first argument to be the object (reference) or package (string) it is being invoked on.

Re^3: Would someone mind helping me understand this Perl OO code?
by ikegami (Patriarch) on Dec 22, 2009 at 16:10 UTC
    Oops, ignore my earlier post.
    Node->new($ip, $mac_address, $machine);
    is basically the same as
    Node::new('Node', $ip, $mac_address, $machine);
    The main difference is that it checks the parent classes for new if sub Node::new doesn't exist.