What is the difference between -> and :: in Perl

后端 未结 3 1664
北荒
北荒 2021-02-05 05:44

What is the exact difference between :: and -> in Perl?

-> sometimes works where :: does not.

3条回答
  •  独厮守ぢ
    2021-02-05 06:23

    Lots of explanations here, but here is the very simplistic answer for new developers:

    FOO::BAR();  # is calling the class's (aka. package's) default object
    $FOO->BAR(); # is calling an initiated object
    

    An object typically has properties that are often set, where as an uninitiated object uses the default object properties only.

    Say FOO has a property called 'Age' that has a default value of 1 that we can change via a set command earlier in our program. Then we decide to call the package again both ways for fun we could see:

    use FOO;
    $FOO = new FOO(); #new instance of foo 
    $FOO->SetAge(21);
    
    # more code here
    
    print $FOO->GetAge(); # prints 21
    print FOO::GetAge(); # prints 1
    

    What about packages without any stored variables? In many cases there may be no difference at all, but this ultimately depends on how the class is written. In the end it is more complex than that.. and this isn't truly the exact answer, but it is what I believe you are looking for based on your question.

    Just to prevent confusion generally I do not use the classes/packages name when creating an object. If for some reason I don't know what to call it I prefix it with an 'o' so it is clear it is an object and not a class, which is a good practice for any programing language.

    i.e. use

    $oFOO = new FOO(); // new object instance of foo
    

    Hope that helps.

提交回复
热议问题