Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Would someone mind helping me understand this Perl OO code?

by romandas (Pilgrim)
on Dec 22, 2009 at 15:48 UTC ( [id://813906]=perlquestion: print w/replies, xml ) Need Help??

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

Note that I do not own this code. I believe I pulled it from CPAN, and that it rightfully belongs to James MacFarlane. If this is incorrect, let me know and I'll attribute it accordingly. I couldn't find where I originally pulled it from.

Here are the relevant snippets:

#----------------------------------------------------------------- package Node; #----------------------------------------------------------------- sub new { my ($pkg, $ip, $mac, $hostname) = @_; my $obj = {}; bless $obj, $pkg; $obj->IP_Address($ip); $obj->MAC_Address($mac); $obj->Hostname($hostname); return $obj; }

So, from what I see above, Node->new() should be called using 4 arguments. However, when the original author used Node->new(), he did this:

$nodeobj = Node->new($ip, $mac_address, $machine); push(@nodes, $nodeobj);

This only uses three arguments. And if you omit one, then it appears the values would suffer a sort of 'one off' error. But.. the code appears to work fine. What gives?

Update: Thanks all!

Replies are listed 'Best First'.
Re: Would someone mind helping me understand this Perl OO code?
by ikegami (Patriarch) on Dec 22, 2009 at 15:52 UTC
    If you assign a list of 3 values to a list of 4 scalars, the 4th scalar will be undefined.

    ( True, but irrelevant to the parent post. oops! )

      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.

        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)

        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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2024-04-16 10:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found