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?
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?
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With