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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |