My fellow monks,

I have witnessed the following in our codebase at $work:

sub new { $_[0]->{class} = shift; validate( @_, ... ); my $self = {}; return bless $self, __PACKAGE__; }

(As an aside, this is the same programmer who inspired A class that cannot be subclassed.)

To my dismay, this actually works. The effect is:

What's interesting to me about this is that the shift happens before perl determines what $_[0] is for the assignment. If it didn't, it would always die because the class name, a string, wouldn't be allowed as a hash reference. My question is, is this reliable? Can we safely assume that this will not change in some future version of Perl? More to the point, can I reject this construct in a code review on the grounds that it can't be trusted to continue to do what it does now?

When I pasted this snippet into the CB, there was some question about why one would want to do this. As it turns out, the reason is "validation". The contents of @_ get passed to to something based on Params::Validate, which then ensures that the 'class' is what it ought to be.

If the hash ref in question were later blessed into the given class, I could see wanting to remember the original class in case the object is reblessed into something else. That's not what's going on in this case, however.

I thank you for your insights.


In reply to Will "$_[0]=shift" always resolve shift first? by kyle

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.