Faking "Private" methods with Perl

Although Perl doesn’t really do the whole OO concept of private/public access modifiers, it’s somewhat possible to approximate them using subroutine references.

my $print_rev = sub { print scalar reverse $_[0]; };

Now we have a lexically scoped variable, visible only within its package, containing a reference to an anonymous sub.

Within our class/package, we call it by doing something like:


Voila! Instant private method!

note: this is partway to creating closures, which are functions declared at runtime with, with variables passed as parameter. I might mention them some other time.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s