[edit] Storing and retrieving data from complex data structures
This chapter will very briefly cover complex data structures, now that we have covered hashes and arrays. Complex data structures are simply variables that are built with multiple levels of arrays and/or hashes. Let's use a book as an example for our complex data structure.
[% book = { 'tableofcontents' => [ 'chapter1', 'chapter2', 'chapter3' ], 'chapter1' => { 'title' => 'Chapter 1 Title', 'content' => 'Content for chapter 1' }, 'chapter2' => { 'title' => 'Chapter 2 Title', 'content' => 'Content for chapter 2' }, 'chapter3' => { 'title' => 'Chapter 3 Title', 'content' => 'Content for chapter 3' } }; %]
The example above creates a hash variable called book, however, the values associated with each key are arrays and hashes instead of a conventional scalar content. The key 'tableofcontents' stores an array with the list of chapters. The keys 'chapter1', 'chapter2' and 'chapter3' each store a hash. Each chapter stores a title and content. The rules of constructing arrays and hashes still apply to the formation of complex data structures. With our book variable created, we will now print out different parts of the book.
[% book = { 'tableofcontents' => [ 'chapter1', 'chapter2', 'chapter3' ], 'chapter1' => { 'title' => 'Chapter 1 Title', 'content' => 'This is the Chapter 1 text.' }, 'chapter2' => { 'title' => 'Chapter 2 Title', 'content' => 'This is the Chapter 2 text.' }, 'chapter3' => { 'title' => 'Chapter 3 Title', 'content' => 'This is the Chapter 3 text.' } }; book.tableofcontents.1 _ "\n"; book.chapter3.content _ "\n"; %]
The example above will result in the output below:
chapter2 This is the Chapter 3 text.
The two new lines added above prints out two different parts of the complex variable book. The first new line book.tableofcontents.1 fetches the value with the index of 1 from the array associated with the key 'tableofcontents'. Here is another way to look at it. The value associated with the key 'tableofcontents' is first retrieved. In this case it is an array of 'chapter1', 'chapter2' and 'chapter3'. Then the value with the index of 1 is retrieved from the array, which in this case is 'chapter2'. The following line book.chapter3.content retrieves the value associated with the key 'chapter3' from the array book, which is another hash. From this hash, it retrieves the value with the key 'content'. So the string 'This is the Chapter 3 text is returned.'