Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: read/write associative array from/to file



On Jan 3,  3:12am, Thomas Gstadtner wrote:
}
} I want to read and write an associative array from/to a file, i.e. a
} very simple key-value database. Is this possible; if so, how?

Zsh doesn't have perl-style DBM bindings if that's what you're after,
though it should be possible to write that as a module if someone is
feeling ambitious.

} If not, what would be the most practical solution to work with a file
} like this?
} ---
} key1 value1
} key2 value2
} key3 value3
} ...
} ---

Assuming that the only space is the one that separates keys from values
on every line, you can populate an associative array like so:

    tyepset -A dbary
    dbary=( ${=${(f)"$(<file)"}} )

If the values can have spaces but the keys cannot, then a loop:

    tyepset -A dbary
    while read k v; do dbary[$k]="$v"; done < file

There are some syntactic restrictions on things that can be easily used
as associative array keys; if your keys contain punctuation characters,
particularly quotes, you may want to think twice about doing this in zsh
at all.

Having populated dbary from the file, we join the discussion already in
progress ...

On Jan 3,  9:02am, Wayne Davison wrote:
} Subject: Re: read/write associative array from/to file
}
} On Tue, Jan 3, 2012 at 1:40 AM, Jérémie Roquet <arkanosis@xxxxxxxxx> wrote:
} 
} > echo "myArray=(${(kv)myArray})" >| $db
} 
} That works if there are no spaces or special characters involved.  You
} could change that line to remove the double quotes and add (q) or (q-) to
} the expansion, and it would handle those:
} 
} typeset -A myArray
} myArray=(
} foo 1\ is\ the\ loneliest\ number
} bar 42\ isn\'t\ really\ the\ ultimate\ answer
} )
} echo myArray=\(${(kvq-)myArray}\) >/tmp/myArray

Wayne is correct here, but the easiest way to store/reload a parameter
to/from a file is with "typeset -p":

    typeset -p dbary > dbfile

writes a well-formed declaration and assignment to dbfile, which can be
read back with

    source dbfile

As was mentioned, this assumes that you can write the dbfile to a secure
location and be confident that no one tampers with it before you source
it back again.



Messages sorted by: Reverse Date, Date, Thread, Author