Commit | Line | Data |
---|---|---|
2b69d0c2 | 1 | ;# shellwords.pl |
2 | ;# | |
3 | ;# Usage: | |
4 | ;# require 'shellwords.pl'; | |
08b96d1f | 5 | ;# @words = shellwords($line); |
2b69d0c2 | 6 | ;# or |
08b96d1f | 7 | ;# @words = shellwords(@lines); |
2b69d0c2 | 8 | ;# or |
08b96d1f | 9 | ;# @words = shellwords(); # defaults to $_ (and clobbers it) |
9ef589d8 | 10 | |
11 | sub shellwords { | |
08b96d1f | 12 | local *_ = \join('', @_) if @_; |
13 | my (@words, $snippet); | |
9ef589d8 | 14 | |
08b96d1f | 15 | s/\A\s+//; |
9ef589d8 | 16 | while ($_ ne '') { |
08b96d1f | 17 | my $field = substr($_, 0, 0); # leave results tainted |
9ef589d8 | 18 | for (;;) { |
08b96d1f | 19 | if (s/\A"(([^"\\]|\\.)*)"//s) { |
20 | ($snippet = $1) =~ s#\\(.)#$1#sg; | |
9ef589d8 | 21 | } |
08b96d1f | 22 | elsif (/\A"/) { |
2b69d0c2 | 23 | die "Unmatched double quote: $_\n"; |
24 | } | |
08b96d1f | 25 | elsif (s/\A'(([^'\\]|\\.)*)'//s) { |
26 | ($snippet = $1) =~ s#\\(.)#$1#sg; | |
9ef589d8 | 27 | } |
08b96d1f | 28 | elsif (/\A'/) { |
2b69d0c2 | 29 | die "Unmatched single quote: $_\n"; |
30 | } | |
08b96d1f | 31 | elsif (s/\A\\(.)//s) { |
9ef589d8 | 32 | $snippet = $1; |
33 | } | |
08b96d1f | 34 | elsif (s/\A([^\s\\'"]+)//) { |
9ef589d8 | 35 | $snippet = $1; |
36 | } | |
37 | else { | |
08b96d1f | 38 | s/\A\s+//; |
9ef589d8 | 39 | last; |
40 | } | |
41 | $field .= $snippet; | |
42 | } | |
43 | push(@words, $field); | |
44 | } | |
08b96d1f | 45 | return @words; |
9ef589d8 | 46 | } |
47 | 1; |