mirod has asked for the wisdom of the Perl Monks concerning the following question:
I want to split strings into arrays with the same rules as the shell.
I have a configuration file in which I want to allow users to enter options, possibly several options at once, that will be used in a system call. The think is, I want to use the list form of system (so I can accomodate filenames with fancy characters in them for example). So I think I need to parse the strings in the config file, and split them up as lists of arguments. In fact the exact same process that generates @ARGV from the command line.
I understand that this is shell dependant, so I really just want to allow the usual bareword and quoted arguments.
I have found 2 ways to do this: fork out a perl process and get the @ARGV back, which strikes me a extremely ugly, or use a regexp (see below).
My question is: is there a simpler (and already debugged!) way? I could not find anything in Regexp::Common, nor in any of the Getopt::* modules.
Here is a piece of code that seems to work, comments are also welcome:
#!/usr/bin/perl -w use strict; use Test::More qw(no_plan); while(my $args= <DATA>) { chomp $args; my @expected= map { chomp; $_ } `perl -e'print join "\n", \@ARGV' +-- $args`; my @parsed= parse_args( $args); ok( eq_array( \@parsed, \@expected), $args) or diag( " expected: ", display_array( @expected), "\n", " got : ", display_array( @parsed), "\n" ); } sub parse_args { my $args= shift; my @args; while( $args=~ s{^\s* (?: '((?:\\.|[^'])+)' # ' quoted args |"((?:\\.|[^"])+)" # " quoted args |((?:\\.|\S)+) # bareword args )} {}x ) { # only one of $1, $2, $3 is defined, get it my $arg=defined $1 ? $1 : defined $2 ? $2 : defined $3 ? $3 : +undef; $arg=~ s{\\}{}g; # unescape \ push @args, $arg; } return @args; } sub display_array { return '[empty]' unless @_; return "/" . join( '/ - /', @_), "/"; } __DATA__ -f --flag -f -l -fl -f val --file val -- file\ with\ spaces and more\ file\ with\ spaces ' +an other "file name" here ' "and here " foo\ foo\ bar 'foo bar' 'foo bar' foo\ bar "foo bar" "foo \" bar" foo\ bar 'foo bar' 'foo bar' foo\ bar "foo bar" "foo \" bar" foobar - f val
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Parsing strings into @ARGV
by eserte (Deacon) on Apr 23, 2004 at 15:03 UTC | |
|
Re: Parsing strings into @ARGV
by halley (Prior) on Apr 23, 2004 at 14:56 UTC | |
by mirod (Canon) on Apr 23, 2004 at 15:00 UTC | |
|
Re: Parsing strings into @ARGV
by Corion (Patriarch) on Apr 23, 2004 at 15:05 UTC | |
by mirod (Canon) on Apr 23, 2004 at 15:23 UTC | |
by Abigail-II (Bishop) on Apr 23, 2004 at 16:12 UTC | |
by mirod (Canon) on Apr 23, 2004 at 16:15 UTC | |
by Abigail-II (Bishop) on Apr 23, 2004 at 16:45 UTC | |
| |
by mirod (Canon) on Apr 23, 2004 at 16:24 UTC | |
by chromatic (Archbishop) on Apr 23, 2004 at 16:34 UTC | |
|
Re: Parsing strings into @ARGV
by meonkeys (Chaplain) on Apr 24, 2004 at 01:33 UTC |