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