This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Fixes to compile Perl with g++ and DEBUGGING.
[perl5.git] / lib / Shell.pm
CommitLineData
a0d0e21e 1package Shell;
3b825e41 2use 5.006_001;
8d5b6de5
CT
3use strict;
4use warnings;
d0b4fbd9
DM
5use File::Spec::Functions;
6
96412ebc 7our($capture_stderr, $raw, $VERSION, $AUTOLOAD);
a0d0e21e 8
ff5c8f2a 9$VERSION = '0.7';
8d5b6de5 10
605870ff 11sub new { bless \my $foo, shift }
8d5b6de5 12sub DESTROY { }
4633a7c4 13
a0d0e21e
LW
14sub import {
15 my $self = shift;
16 my ($callpack, $callfile, $callline) = caller;
17 my @EXPORT;
18 if (@_) {
ff5c8f2a 19 @EXPORT = @_;
8d5b6de5 20 } else {
ff5c8f2a 21 @EXPORT = 'AUTOLOAD';
a0d0e21e 22 }
8d5b6de5
CT
23 foreach my $sym (@EXPORT) {
24 no strict 'refs';
a0d0e21e
LW
25 *{"${callpack}::$sym"} = \&{"Shell::$sym"};
26 }
8d5b6de5 27}
a0d0e21e 28
ff5c8f2a
AF
29# NOTE: this is used to enable constant folding in
30# expressions like (OS eq 'MSWin32') and
31# (OS eq 'os2') just like it happened in 0.6 version
32# which used eval "string" to install subs on the fly.
33use constant OS => $^O;
34
35=begin private
36
2b63cd5c
RGS
37=over
38
ff5c8f2a
AF
39=item B<_make_cmd>
40
41 $sub = _make_cmd($cmd);
42 $sub = $shell->_make_cmd($cmd);
43
44Creates a closure which invokes the system command C<$cmd>.
45
2b63cd5c
RGS
46=back
47
48=end private
49
ff5c8f2a
AF
50=cut
51
52sub _make_cmd {
8d5b6de5 53 shift if ref $_[0] && $_[0]->isa( 'Shell' );
ff5c8f2a 54 my $cmd = shift;
d0b4fbd9 55 my $null = File::Spec::Functions::devnull();
c4a2e7a5 56 $Shell::capture_stderr ||= 0;
ff5c8f2a
AF
57 # closing over $^O, $cmd, and $null
58 return sub {
59 shift if ref $_[0] && $_[0]->isa( 'Shell' );
60 if (@_ < 1) {
61 $Shell::capture_stderr == 1 ? `$cmd 2>&1` :
62 $Shell::capture_stderr == -1 ? `$cmd 2>$null` :
63 `$cmd`;
64 } elsif (OS eq 'os2') {
65 local(*SAVEOUT, *READ, *WRITE);
66
67 open SAVEOUT, '>&STDOUT' or die;
68 pipe READ, WRITE or die;
69 open STDOUT, '>&WRITE' or die;
70 close WRITE;
71
72 my $pid = system(1, $cmd, @_);
73 die "Can't execute $cmd: $!\n" if $pid < 0;
74
75 open STDOUT, '>&SAVEOUT' or die;
76 close SAVEOUT;
77
78 if (wantarray) {
79 my @ret = <READ>;
80 close READ;
81 waitpid $pid, 0;
82 @ret;
83 } else {
84 local($/) = undef;
85 my $ret = <READ>;
86 close READ;
87 waitpid $pid, 0;
88 $ret;
89 }
90 } else {
91 my $a;
92 my @arr = @_;
93 unless( $Shell::raw ){
94 if (OS eq 'MSWin32') {
95 # XXX this special-casing should not be needed
96 # if we do quoting right on Windows. :-(
97 #
98 # First, escape all quotes. Cover the case where we
99 # want to pass along a quote preceded by a backslash
100 # (i.e., C<"param \""" end">).
101 # Ugly, yup? You know, windoze.
102 # Enclose in quotes only the parameters that need it:
103 # try this: c:> dir "/w"
104 # and this: c:> dir /w
105 for (@arr) {
106 s/"/\\"/g;
107 s/\\\\"/\\\\"""/g;
108 $_ = qq["$_"] if /\s/;
109 }
110 } else {
111 for (@arr) {
112 s/(['\\])/\\$1/g;
113 $_ = $_;
114 }
96412ebc 115 }
ff5c8f2a
AF
116 }
117 push @arr, '2>&1' if $Shell::capture_stderr == 1;
118 push @arr, '2>$null' if $Shell::capture_stderr == -1;
119 open(SUBPROC, join(' ', $cmd, @arr, '|'))
120 or die "Can't exec $cmd: $!\n";
121 if (wantarray) {
122 my @ret = <SUBPROC>;
123 close SUBPROC; # XXX Oughta use a destructor.
124 @ret;
125 } else {
126 local($/) = undef;
127 my $ret = <SUBPROC>;
128 close SUBPROC;
129 $ret;
130 }
131 }
132 };
133 }
134
135sub AUTOLOAD {
136 shift if ref $_[0] && $_[0]->isa( 'Shell' );
137 my $cmd = $AUTOLOAD;
138 $cmd =~ s/^.*:://;
139 no strict 'refs';
140 *$AUTOLOAD = _make_cmd($cmd);
a0d0e21e
LW
141 goto &$AUTOLOAD;
142}
143
1441;
8d5b6de5 145
a5f75d66
AD
146__END__
147
148=head1 NAME
149
150Shell - run shell commands transparently within perl
151
152=head1 SYNOPSIS
153
96412ebc
WL
154 use Shell qw(cat ps cp);
155 $passwd = cat('</etc/passwd');
156 @pslines = ps('-ww'),
157 cp("/etc/passwd", "/tmp/passwd");
158
159 # object oriented
160 my $sh = Shell->new;
161 print $sh->ls('-l');
a5f75d66
AD
162
163=head1 DESCRIPTION
164
96412ebc
WL
165=head2 Caveats
166
167This package is included as a show case, illustrating a few Perl features.
168It shouldn't be used for production programs. Although it does provide a
169simple interface for obtaining the standard output of arbitrary commands,
170there may be better ways of achieving what you need.
171
172Running shell commands while obtaining standard output can be done with the
173C<qx/STRING/> operator, or by calling C<open> with a filename expression that
174ends with C<|>, giving you the option to process one line at a time.
175If you don't need to process standard output at all, you might use C<system>
176(in preference of doing a print with the collected standard output).
177
178Since Shell.pm and all of the aforementioned techniques use your system's
179shell to call some local command, none of them is portable across different
180systems. Note, however, that there are several built in functions and
181library packages providing portable implementations of functions operating
182on files, such as: C<glob>, C<link> and C<unlink>, C<mkdir> and C<rmdir>,
183C<rename>, C<File::Compare>, C<File::Copy>, C<File::Find> etc.
184
185Using Shell.pm while importing C<foo> creates a subroutine C<foo> in the
186namespace of the importing package. Calling C<foo> with arguments C<arg1>,
187C<arg2>,... results in a shell command C<foo arg1 arg2...>, where the
188function name and the arguments are joined with a blank. (See the subsection
189on Escaping magic characters.) Since the result is essentially a command
190line to be passed to the shell, your notion of arguments to the Perl
191function is not necessarily identical to what the shell treats as a
192command line token, to be passed as an individual argument to the program.
193Furthermore, note that this implies that C<foo> is callable by file name
194only, which frequently depends on the setting of the program's environment.
195
196Creating a Shell object gives you the opportunity to call any command
197in the usual OO notation without requiring you to announce it in the
198C<use Shell> statement. Don't assume any additional semantics being
199associated with a Shell object: in no way is it similar to a shell
200process with its environment or current working directory or any
201other setting.
202
203=head2 Escaping Magic Characters
204
205It is, in general, impossible to take care of quoting the shell's
206magic characters. For some obscure reason, however, Shell.pm quotes
207apostrophes (C<'>) and backslashes (C<\>) on UNIX, and spaces and
208quotes (C<">) on Windows.
209
210=head2 Configuration
211
212If you set $Shell::capture_stderr to true, the module will attempt to
213capture the standard error output of the process as well. This is
214done by adding C<2E<gt>&1> to the command line, so don't try this on
215a system not supporting this redirection.
216
217If you set $Shell::raw to true no quoting whatsoever is done.
218
219=head1 BUGS
220
221Quoting should be off by default.
222
223It isn't possible to call shell built in commands, but it can be
224done by using a workaround, e.g. shell( '-c', 'set' ).
225
226Capturing standard error does not work on some systems (e.g. VMS).
227
228=head1 AUTHOR
229
a5f75d66
AD
230 Date: Thu, 22 Sep 94 16:18:16 -0700
231 Message-Id: <9409222318.AA17072@scalpel.netlabs.com>
232 To: perl5-porters@isu.edu
233 From: Larry Wall <lwall@scalpel.netlabs.com>
234 Subject: a new module I just wrote
235
236Here's one that'll whack your mind a little out.
237
238 #!/usr/bin/perl
239
240 use Shell;
241
242 $foo = echo("howdy", "<funny>", "world");
243 print $foo;
244
245 $passwd = cat("</etc/passwd");
246 print $passwd;
247
248 sub ps;
249 print ps -ww;
250
2359510d 251 cp("/etc/passwd", "/etc/passwd.orig");
a5f75d66
AD
252
253That's maybe too gonzo. It actually exports an AUTOLOAD to the current
254package (and uncovered a bug in Beta 3, by the way). Maybe the usual
255usage should be
256
257 use Shell qw(echo cat ps cp);
258
a5f75d66
AD
259Larry Wall
260
96412ebc
WL
261Changes by Jenda@Krynicky.cz and Dave Cottle <d.cottle@csc.canterbury.ac.nz>.
262
263Changes for OO syntax and bug fixes by Casey West <casey@geeknest.com>.
253924a2 264
96412ebc 265C<$Shell::raw> and pod rewrite by Wolfgang Laun.
8d5b6de5 266
ff5c8f2a
AF
267Rewritten to use closures rather than C<eval "string"> by Adriano Ferreira.
268
a5f75d66 269=cut