This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Make pp_reverse fetch the lexical $_ from the correct pad
[perl5.git] / lib / dotsh.pl
1 #
2 #   @(#)dotsh.pl                                               03/19/94
3 #
4 # This library is no longer being maintained, and is included for backward
5 # compatibility with Perl 4 programs which may require it.
6 # This legacy library is deprecated and will be removed in a future
7 # release of perl.
8 #
9 # In particular, this should not be used as an example of modern Perl
10 # programming techniques.
11 #
12 #   Author: Charles Collins
13 #
14 #   Description:
15 #      This routine takes a shell script and 'dots' it into the current perl
16 #      environment. This makes it possible to use existing system scripts
17 #      to alter environment variables on the fly.
18 #
19 #   Usage:
20 #      &dotsh ('ShellScript', 'DependentVariable(s)');
21 #
22 #         where
23 #
24 #      'ShellScript' is the full name of the shell script to be dotted
25 #
26 #      'DependentVariable(s)' is an optional list of shell variables in the
27 #         form VARIABLE=VALUE,VARIABLE=VALUE,... that 'ShellScript' is
28 #         dependent upon. These variables MUST be defined using shell syntax.
29 #
30 #   Example:
31 #      &dotsh ('/foo/bar', 'arg1');
32 #      &dotsh ('/foo/bar');
33 #      &dotsh ('/foo/bar arg1 ... argN');
34 #
35
36 sub dotsh {
37    local(@sh) = @_;
38    local($tmp,$key,$shell,$command,$args,$vars) = '';
39    local(*dotsh);
40    undef *dotsh;
41    $dotsh = shift(@sh);
42    @dotsh = split (/\s/, $dotsh);
43    $command = shift (@dotsh);
44    $args = join (" ", @dotsh);
45    $vars = join ("\n", @sh);
46    open (_SH_ENV, "$command") || die "Could not open $dotsh!\n";
47    chop($_ = <_SH_ENV>);
48    $shell = "$1 -c" if ($_ =~ /^\#\!\s*(\S+(\/sh|\/ksh|\/zsh|\/csh))\s*$/);
49    close (_SH_ENV);
50    if (!$shell) {
51       if ($ENV{'SHELL'} =~ /\/sh$|\/ksh$|\/zsh$|\/bash$|\/csh$/) {
52          $shell = "$ENV{'SHELL'} -c";
53       } else {
54          print "SHELL not recognized!\nUsing /bin/sh...\n";
55          $shell = "/bin/sh -c";
56       }
57    }
58    if (length($vars) > 0) {
59       open (_SH_ENV, "$shell \"$vars && . $command $args && set \" |") || die;
60    } else {
61       open (_SH_ENV, "$shell \". $command $args && set \" |") || die;
62    }
63
64    while (<_SH_ENV>) {
65        chop;
66        m/^([^=]*)=(.*)/s;
67        $ENV{$1} = $2;
68    }
69    close (_SH_ENV);
70
71    foreach $key (keys(%ENV)) {
72        $tmp .= "\$$key = \$ENV{'$key'};" if $key =~ /^[A-Za-z]\w*$/;
73    }
74    eval $tmp;
75 }
76 1;