This constructor is written in a confusing way, so you're right to be confused about it. About your questions:

  1. The comma operator combines expressions, so shift, shift could just be written as (shift,shift), which is the same as "take the first two elements off of @_". This should have better been written as splice @_, 0, 2.
  2. chromatic will wail and rail against ref($class)||$class, but it is a well-entrenched idiom to allow construction of a fresh object from an old object. ref($class) returns the package name of an object or undef if $class is not a reference. This is to make both of these invocations work:
    my $obj = My::Class->new(...); my $other_obj = $obj->new(...);
    Whether or how that can make sense has been discussed here and elsewhere. In most cases, you can just leave it out.
  3. The first parameter of new() is the class name, but it's not hidden, it's there in plain sight:
    My::Class->new("a","b");

    is the same as

    My::Class::new("My::Class","a","b");

    except that inheritance is not respected in the second case.

  4. The while loop is taking the first two elements in @_ and putting them into the hash referenced by $self. Then it removes the first two elements of @_. This loop could have been written more succinct and clear as:
    $self = { @_ }; # or %$self = @_;

In short, the whole constructor could have been written as:

sub new { my ($class,%args) = @_; my $self = \%args; bless $self, ref($class)||$class; };

In reply to Re: confusing constructor code by Corion
in thread confusing constructor code by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.