Chapter 14. Data Persistence
My programs can share their data, either with other programs or with future invocations of themselves. To make that possible, I store the data outside of the program’s memory and then read it from that source to recreate it. I can put that data in a file or a database, send it over a network connection, or anything else I want to do with it.
I can even share data between different programs. For anything except
for simple applications, I’d probably want to use a robust database server
and the DBI module. I won’t cover proper database
servers such as MySQL, PostgreSQL, or Oracle. Perl works with those through
DBI, and there’s already a great book for that in Further Reading,” at the end of the chapter. This chapter is
about lightweight techniques I can use when I don’t need a full server
backend.
Flat Files
Conceptually and practically, the easiest way to save and reuse data is to write it as text to a file. I don’t need much to do it, and I can inspect the file, change the data if I like, and send it to other people without worrying about low-level details like byte ordering or internal data sizes. When I want to reuse the data, I read it back into the program. Even if I don’t use a real file, I can still use these techniques to send the data down a socket or in an email.
pack
The pack built-in takes
data and turns it into a single string by using a template
string to decide how to put the data together. It’s similar to
sprintf, although like its name suggests, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access