Commit | Line | Data |
a0d0e21e |
1 | package Env; |
2 | |
3 | =head1 NAME |
4 | |
cb1a09d0 |
5 | Env - perl module that imports environment variables |
6 | |
7 | =head1 SYNOPSIS |
8 | |
9 | use Env; |
10 | use Env qw(PATH HOME TERM); |
a0d0e21e |
11 | |
12 | =head1 DESCRIPTION |
13 | |
14 | Perl maintains environment variables in a pseudo-associative-array |
15 | named %ENV. For when this access method is inconvenient, the Perl |
16 | module C<Env> allows environment variables to be treated as simple |
17 | variables. |
18 | |
19 | The Env::import() function ties environment variables with suitable |
20 | names to global Perl variables with the same names. By default it |
21 | does so with all existing environment variables (C<keys %ENV>). If |
22 | the import function receives arguments, it takes them to be a list of |
23 | environment variables to tie; it's okay if they don't yet exist. |
24 | |
25 | After an environment variable is tied, merely use it like a normal variable. |
26 | You may access its value |
27 | |
28 | @path = split(/:/, $PATH); |
29 | |
30 | or modify it |
31 | |
32 | $PATH .= ":."; |
33 | |
34 | however you'd like. |
35 | To remove a tied environment variable from |
36 | the environment, assign it the undefined value |
37 | |
38 | undef $PATH; |
39 | |
40 | =head1 AUTHOR |
41 | |
1fef88e7 |
42 | Chip Salzenberg E<lt>F<chip@fin.uucp>E<gt> |
a0d0e21e |
43 | |
44 | =cut |
45 | |
46 | sub import { |
47 | my ($callpack) = caller(0); |
48 | my $pack = shift; |
49 | my @vars = @_ ? @_ : keys(%ENV); |
40da2db3 |
50 | return unless @vars; |
a0d0e21e |
51 | |
40da2db3 |
52 | eval "package $callpack; use vars qw(" |
53 | . join(' ', map { '$'.$_ } @vars) . ")"; |
54 | die $@ if $@; |
a0d0e21e |
55 | foreach (@vars) { |
56 | tie ${"${callpack}::$_"}, Env, $_ if /^[A-Za-z_]\w*$/; |
57 | } |
58 | } |
59 | |
60 | sub TIESCALAR { |
61 | bless \($_[1]); |
62 | } |
63 | |
64 | sub FETCH { |
65 | my ($self) = @_; |
66 | $ENV{$$self}; |
67 | } |
68 | |
69 | sub STORE { |
70 | my ($self, $value) = @_; |
71 | if (defined($value)) { |
72 | $ENV{$$self} = $value; |
73 | } else { |
74 | delete $ENV{$$self}; |
75 | } |
76 | } |
77 | |
78 | 1; |