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

后端 未结 4 1707
我在风中等你
我在风中等你 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:37

    Using new Some::Class is called "indirect" method invocation, and it's bad because it introduces some ambiguity into the syntax.

    One reason it can fail is if you have an array or hash of objects. You might expect

    dosomethingwith $hashref->{obj}
    

    to be equal to

    $hashref->{obj}->dosomethingwith();
    

    but it actually parses as:

    $hashref->dosomethingwith->{obj}
    

    which probably isn't what you wanted.

    Another problem is if there happens to be a function in your package with the same name as a method you're trying to call. For example, what if some module that you use'd exported a function called dosomethingwith? In that case, dosomethingwith $object is ambiguous, and can result in puzzling bugs.

    Using the -> syntax exclusively eliminates these problems, because the method and what you want the method to operate upon are always clear to the compiler.

提交回复
热议问题