eyepopslikeamosquito has asked for the wisdom of the Perl Monks concerning the following question:
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:
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?# 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;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Mimicking Unix shell quoting in Perl
by Anonymous Monk on Aug 20, 2007 at 08:04 UTC | |
by halley (Prior) on Aug 20, 2007 at 13:17 UTC | |
by bart (Canon) on Aug 21, 2007 at 10:19 UTC | |
|
Re: Mimicking Unix shell quoting in Perl
by brx (Pilgrim) on Aug 20, 2007 at 15:39 UTC | |
|
Re: Mimicking Unix shell quoting in Perl
by djerius (Beadle) on Aug 20, 2007 at 14:48 UTC |