Privacy

Symbols in Perl are freely accessible; privacy is not enforced. The online documentation says, rather colorfully, “Perl does not enforce private and public parts of its modules as you may have been used to in other languages like C++, Ada, or Modula-17. Perl doesn’t have an infatuation with enforced privacy. It would prefer that you stayed out of its living room because you weren’t invited, not because it has a shotgun.”[27]

In addition to accessing a foreign package’s existing variables or subroutines, a package can easily create new names in another package’s namespace, as we saw earlier. Consider

package Test;
# Create a variable and a subroutine in another package
$main::foo = 10;
sub main::myFunc {  
    print "Hello \n";
}

package main;
myFunc();   #  prints "Hello"

Although this is not a very kosher thing to do in a normal application, this facility can be put to good use if applied in a controlled manner. You can use it to import foreign package symbol names into your own namespace; we will study this in the next section.

Enforcing Privacy

You can use the my operator at file scope to get unassailably private variables. Because they are not associated in any way with a package, they cannot be accessed from a different scope (in this case, file scope). But because they don’t have anything to do with packages, they are restricted at most to file boundaries. Consider

package A; my $a = 10; # A lexical variable package B; print $A::a; # No such variable in package A print $a; # ...

Get Advanced Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.