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