use warnings; use strict; =head2 getopts_from_str(string, argumentspec, hashref) This function uses L's C to parse the given I, and then applies C from L to the result, passing it the I and I. If C returns a true value, this function returns an arrayref of the arguments remaining after applying C, and if C reports an error by returning false, this function also returns false. =cut use Text::ParseWords 'shellwords'; use Getopt::Std 'getopts'; sub getopts_from_str { my ($str,$argspec,$hashref) = @_; local @ARGV = shellwords($str); return unless getopts($argspec, $hashref); return [@ARGV]; } # Example Code: my $optstr = q{ -a "hello world" -b "some \"text\"" -c 'abc def' }; my $argv = getopts_from_str($optstr, 'a:b:c', \my %opts) or die "bad options"; use Data::Dumper; print Dumper(\%opts, $argv); __END__ $VAR1 = { 'b' => 'some "text"', 'a' => 'hello world', 'c' => 1 }; $VAR2 = [ 'abc def' ]; #### use warnings; use strict; use Data::Dump 'pp'; use Text::ParseWords 'shellwords'; use Getopt::Std 'getopts'; my $stdin = q{ -a "hello world" -b "some \"text\"" -c 'abc def' }; my %opts; { # for local; avoid messing with global @ARGV local @ARGV = shellwords($stdin); pp \@ARGV; getopts('a:b:c', \%opts) or die "bad options"; pp \%opts, \@ARGV; } __END__ ["-a", "hello world", "-b", "some \"text\"", "-c", "abc def"] ( { a => "hello world", b => "some \"text\"", c => 1 }, ["abc def"], )