In the recent discussion of ref($class)||$class, it was proposed that the idiom somehow makes it worse when a method is accidentally called as a function. I don't quite follow this, but quickly tried a workaround:
# instead of my $class = shift; my $self = bless {}, ref($class) || $class; # try my $self = bless {}, ref($_[0]) || @_
Note that || does properly propagate list context onto its right operand. The problem is that bless has a "$;$" prototype, so there isn't list context, there's scalar context instead. So calling it as a function results in a blessing into class "0" :)

open also suffers from this (it has a "*;$@" prototype). So if you want a sub to do some processing and then turn around and open a file passing through its parameters to open, you can't do:

sub foo { # some stuff open my $fh, @_; return $fh; }
Instead you need:
sub foo { # some stuff my $fh; if (@_ == 1) { open $fh, $_[0]; } else { open $fh, $_[0], $_[1], @_[2..$#_]; } return $fh; }
which IMO is real ugly (TM).

What bothers me most is that I can't think of any good reason *why* the optional args should have scalar context for either bless or open. Prototypes of "$@" and "*@" would be just as good in any case I can think of. I can't help but think that someone fell prey to what I call prototypitis; that is, using prototypes to describe what a function expects, rather than using them to control how a function is called.


In reply to multi-arg bless by ysth

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.