What is the difference between new Some::Class and Some::Class->new() in Perl?

后端 未结 4 1709
我在风中等你
我在风中等你 2020-11-29 08:27

Many years ago I remember a fellow programmer counselling this:

new Some::Class;    # bad! (but why?)

Some::Class->new(); # good!

Sadly

4条回答
  •  被撕碎了的回忆
    2020-11-29 08:48

    See Indirect Object Syntax in the perlobj documentation for an explanation of its pitfalls. freido's answer covers one of them (although I tend to avoid that with explicit parens around my function calls).

    Larry once joked that it was there to make the C++ feel happy about new, and although people will tell you not to ever use it, you're probably doing it all the time. Consider this:

    print FH "Some message";
    

    Have you ever wondered my there was no comma after the filehandle? And there's no comma after the class name in the indirect object notation? That's what's going on here. You could rewrite that as a method call on print:

    FH->print( "Some message" );
    

    You may have experienced some weirdness in print if you do it wrong. Putting a comma after the explicit file handle turns it into an argument:

    print FH, "some message";     # GLOB(0xDEADBEEF)some message
    

    Sadly, we have this goofiness in Perl. Not everything that got into the syntax was the best idea, but that's what happens when you pull from so many sources for inspiration. Some of the ideas have to be the bad ones.

提交回复
热议问题