On Aug 12, 2010, at 10:55 AM, Rein Henrichs wrote:
> Excerpts from Paul Nasrat's message of Thu Aug 12 06:45:52 -0700 2010:
>> You might use shellwords to handle the quoting.
>>
>>>> require 'shellwords'
>>>> l = %q(printer-make-and-model='Brother HL-2060 Foomatic/hpijs-pcl5e
>>>> (recommended)' printer-state=3 printer-state-change-time=1266621145
>>>> printer-state-reasons=none printer-type=8564756)
>>>> Shellwords.shellwords(l)
>> => ["printer-make-and-model=Brother HL-2060 Foomatic/hpijs-pcl5e
>> (recommended)", "printer-state=3",
>> "printer-state-change-time=1266621145", "printer-state-reasons=none",
>> "printer-type=8564756"]
>>
>> Paul
>
> Paul, shellwords.rb is one of the many great but little-known Ruby
> standard library tools. Going a little further, we can turn a string of
> shell-quoted key/value pairs separated by an '=' into a hash using:
>
> require 'shellwords'
>
> shellwords = Shellwords.shellwords(your_string)
> pairs = shellwords.map{ |s| s.split('=', 2) }.flatten
> Hash[*pairs]
>
> This may be a little daunting, so let's break it down:
>
> 1) shellwords = Shellwords.shellwords(your_string) turns the string into
> an array of tokens, assuming it's been assigned to your_string.
>
> 2) pairs.map{|s| s.split('=', 2)} takes each string in turn and splits
> it on the first '=', returning a new array containing arrays of
> [before-the-equals, after-the-equals] pairs. Splitting on the first '='
> avoids any possible bugs where there is an = in the value.
>
> 3) .flatten flattens this array of arrays into an array that looks like [
> key, value,
> key, value, ... ]. We'll need this for step 4.
>
> 4) Hash[1, 2, 3, 4] turns the arguments into a hash: { 1 => 2, 3 => 4 }.
> We use this to turn the array above into a Hash. The * is used to
> turn the array into a series of arguments, because Hash[[1,2,3,4]]
> doesn't work, but Hash[*[1,2,3,4]] does. (I often think of * in this
> context as the "unary unarray operator".)
Thanks both of you for the help. It looks like this will do 40% of the work
for me.
--
You received this message because you are subscribed to the Google Groups
"Puppet Users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/puppet-users?hl=en.