Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Howto keep private methods private?

by citromatik (Curate)
on Sep 14, 2007 at 09:29 UTC ( [id://638978]=note: print w/replies, xml ) Need Help??


in reply to Howto keep private methods private?

In Perl Hacks, chromatic gives a very instructive solution that uses Attribute::Handlers. This is the example given:

package Class::HideMethods; use strict; use warnings; use Attribute::Handlers; sub import { my ($self,$ref) = @_; my $package = caller(); $prefixes{ $package } = $ref; } sub gen_prefix { my $invalid_chars = "\0\r\n\f\b"; my $prefix; for (1..5){ my $chars_pos = int (rand(length($invalid_chars))); $prefix .= substr ($invalid_chars, $char_pos, 1); } return $prefix; } package UNIVERSAL; sub Private :ATTR { my ($package, $symbol, $referent, $attr, $data, $phase) = @_; my $name = *{ $symbol }{NAME}; my $newname = Class::HideMethods::gen_prefix ($package) . $name; my @refs = map { *$symbol{$_}} qw (HASH SCALAR ARRAY GLOB); *$symbol = do {local *symbol}; no strict 'refs'; *{ $package . '::' . $newname } = $referent; *{ $package . '::' . $name } = $_ for @refs; $prefixes{ $package }{$name} = $newname; } 1;

To use this module:

package SecretClass; my %methods; use Class::HideMethods \%methods; sub new { bless {}, shift } sub hello :Private { return 'hello' } sub goodbye { return 'goodbye' } sub public_hello { my $self = shift; my $hello = $methods{hello} $self -> $hello(); } 1;

To prove that it works:

use Test::More tests => 6; my $sc = SecretClass->new(); isa_ok ($sc, 'SecretClass' ); ok (! $sc->can ('hello'), 'hello() should be hidden' ); ok ($sc->can('public_hello'), 'public_hello() should be available'); is ($sc->public_hello(),'hello', '... and should be able to call hello +()' ); ok ($sc->can('goodbye'), 'goodbye() should be available'); is ($sc->goodbye(), 'goodbye', '... and should be callable');

Hope this helps

citromatik

Replies are listed 'Best First'.
Re^2: Howto keep private methods private?
by perl-diddler (Chaplain) on Sep 14, 2007 at 11:45 UTC
    so, basically that's similar to the variable security mechanisms using random key names.

    lots of different ways...

    I somehow thought the lack of explicit examples of hiding private method names might not been done because it was messier than variable hiding. It is. Not by much, but a smidge. :-)

    Thanks!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://638978]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-20 05:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found