File: Lexical.pm

package info (click to toggle)
libdata-util-perl 0.67-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 556 kB
  • sloc: perl: 2,958; ansic: 416; makefile: 8
file content (97 lines) | stat: -rw-r--r-- 1,723 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package # this is an example for install_subroutine()/uninstall_subroutine().
	Sub::Exporter::Lexical;
use 5.008_001;
use strict;
use warnings;

use Data::Util;
use Carp ();

sub import :method{
	my $class    = shift;
	my $exportee = caller;

	$class->setup_installer($exportee, @_);
}

sub setup_installer :method{
	my($exporter, $exportee, %args) = @_;

	my $exportable_ref = Data::Util::mkopt_hash $args{exports}, 'setup', 'CODE';

	while(my($name, $entity) = each %{$exportable_ref}){
		unless($entity){
			$exportable_ref->{$name} = Data::Util::get_code_ref($exportee, $name, -create);
		}
	}

	Data::Util::install_subroutine($exportee, import => sub :method{
		my $class = shift;

		my $export_ref;
		if(@_){
			$export_ref = {};
			for my $name(@_){
				$export_ref->{$name} = $exportable_ref->{$name}
					or Carp::croak "$name is not exportable in $exportee";
			}

		}
		else{
			$export_ref = $exportable_ref;
		}

		my $into = caller;
		Data::Util::install_subroutine($into, %{$export_ref});

		$^H |= 0x020000; # HINT_LOCALIZE_HH
		my $cleaner = $^H{$exporter .'/'. $into} ||= bless [$into], $exporter;

		push @{$cleaner}, %{$export_ref};

		return;
	});
}

sub DESTROY :method{
	my($self) = @_;

	Data::Util::uninstall_subroutine(@{$self});
}
1;

__END__

=head1 NAME

Sub::Exporter::Lexical - Exports subrtouines lexically

=head1 SYNOPSIS

	package Foo;
	use Sub::Exporter::Lexical
		exports => [
			qw(foo bar),
			baz => \&bar, # i.e. the synonym of bar
		],
	;

	# ...

	{
		use Foo;
		foo(...); # Foo::foo(...)
		bar(...); # Foo::bar(...)
		baz(...); # Foo::bar(...), too

	} # foo, bar and baz are uninstalled

	foo(); # fatal!
	bar(); # fatal!
	baz(); # fatal!

=head1 SEE ALSO

L<Data::Util>.

=cut