Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unimport a function in perl?

Tags:

perl

I'm trying to remove symbols that are imported so that they are unavailable as methods in the object, but no does not seem to work, maybe I don't understand no, or there's another way.

use 5.014;
use warnings;
use Test::More;

# still has carp after no carp
package Test0 {
    use Carp qw( carp );
    sub new {
        my $class = shift;
        my $self  = {};

        carp 'good';

        bless $self, $class;
        return $self;
    }
    no Carp;
}

my $t0 = Test0->new;

ok( ! $t0->can('carp'), 'can not carp');

# below passes correctly
package Test1 {
    use Carp qw( carp );
    use namespace::autoclean;

    sub new {
        my $class = shift;
        my $self  = {};

        carp 'good';

        bless $self, $class;
        return $self;
    }
}
my $t1 = Test1->new;
ok( ! $t1->can('carp'), 'can not carp');
done_testing;

unfortunately I can't use namespace::autoclean because I've been restricted to modules that are only part of core perl (yeah stupid but c'est la vie).

without just rewriting namespace::autoclean is there a way to do this?

like image 457
xenoterracide Avatar asked Apr 24 '12 22:04

xenoterracide


2 Answers

I believe namespace::autoclean deletes the glob:

delete $Test0::{carp};

Without hardcoding the package:

my $pkg = do { no strict 'refs'; \%{ __PACKAGE__."::" } };
delete $pkg->{carp};

If you insist on leaving strict on, you can fool strict (but it's no more or less safe):

my $pkg = \%::;
$pkg = $pkg->{ $_ . '::' } for split /::/, __PACKAGE__;
delete $pkg->{carp};

PS — Why is code from StackOverflow acceptable if code from CPAN isn't?

like image 73
ikegami Avatar answered Oct 20 '22 21:10

ikegami


I know this doesn't directly answer your question, but a simple workaround is not to import the functions in the first place. This will work just fine:

use Carp ();  # import nothing

Carp::carp 'good';
like image 40
Ilmari Karonen Avatar answered Oct 20 '22 21:10

Ilmari Karonen