Mike Thornley
Mike Thornley

Reputation: 421

When accessing modules

I have a question about packages, modules and syntax. When you access a package in the same file I notice you'd use something like....

package test;
$testVar="This is a test";

#and to access it using..

package main;
print($test::testVar);

or simply...

package test;
print($testVar);

Yet when I use this syntax for use with a module, sending an argument, I am supposed to ommit the $ from the start of the print function, yet above I don't. I noticed it didn't work otherwise and I don't know why. My materials don't clarify.

require module;
print(package::sub("argument"));

Why is that?. I'm confused.

Upvotes: 1

Views: 79

Answers (1)

Dancrumb
Dancrumb

Reputation: 27529

The dollar sign here is a sigil that indicates that the named variable is a scalar.

If there is no preceding package declaration, the use of $var_name contains an implied namespace of main, i.e. it is short for $main::var_name. In the case of your example, where you have package main; first, you need to stipulate that the namespace is test, rather than main, so $test::testVar is required.

For a function call, you do not need to use a sigil. If you did, you would use the ampersand (&), but using ampersands when calling functions has fallen out of favour with many programmers.*

As before, sub_name() is a shortened version of main::sub_name()... in the same way, no sigil is needed to call package::sub().

*References as to the use of &:

Upvotes: 5

Related Questions