I'd like to be able to mimic the way the Unix shell tokenizes a command line into what a Perl program sees as @ARGV. This little test program hopefully makes clear what I'd like to achieve:
# Mimic the way the Unix shell breaks up cmdline into @ARGV.
# Before running this script, create a separate test script, g.pl, con
+sisting of:
# for my $a (@ARGV) { print "a=:$a:\n" }
use strict;
use warnings;
### $qq matches a single or double quoted string.
my $qq = qr/'[^'\\]*(?:\\.[^'\\]*)*'|"[^"\\]*(?:\\.[^"\\]*)*"/;
my $cmd = qq{perl g.pl arg1 'arg 2' "arg 3" "arg \\"4" arg5};
print "cmd=:$cmd:\n\n";
my @args = $cmd =~ /$qq|\S+/g;
for my $t (@args) {
if (substr($t, 0, 1) eq "'" || substr($t, 0, 1) eq '"') {
$t = substr($t, 1, -1);
$t =~ s/\\(['"])/$1/g;
}
}
for my $a (@args) { print "a=:$a:\n" }
print "\n";
system($cmd);
print "\n";
system { $^X } @args;
Running this program shows that @args above matches what is seen as @ARGV in g.pl.
However, this feels quite tricky and I've got that old re-inventing the wheel feeling. Is there a better way to do this?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|