Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi there. What's the best way to refer to a function inside a package from within the package functions itself?

I haven't worked with modules much until now, so I've been writing:

package myPackage; sub function1{ #do stuff myPackage->function2($thing) #do stuff } sub function2{ #do stuff }

Does Perl provide a better way to do it?

Replies are listed 'Best First'.
Re: Using functions from their own package
by Athanasius (Archbishop) on Oct 15, 2012 at 02:59 UTC

    Yes, exactly. To elaborate on Anonymous Monk’s answer:

    12:41 >perl -Mstrict -wE "package myPackage; sub function1 { myPackage +::function2('Hi!'); } sub function2 { say qq[@_]; } function1();" Hi! 12:41 >perl -Mstrict -wE "package myPackage; sub function1 { function2 +('Hi!'); } sub function2 { say qq[@_]; } function1();" Hi! 12:41 >perl -Mstrict -wE "package myPackage; sub function1 { myPackage +->function2('Hi!'); } sub function2 { say qq[@_]; } function1();" myPackage Hi! 12:41 >

    Within the package, prepending myPackage:: to a function name is merely redundant. But prepending myPackage-> changes the behaviour: it passes the package name to the function as the first argument.

    Hope that helps,

    Athanasius <°(((><contra mundum

      Ah, thank you
Re: Using functions from their own package
by Anonymous Monk on Oct 15, 2012 at 02:28 UTC

    You should call functions by using  foo() or myPackage::foo()

    You should reserve use of -> for methods only