in reply to Re: Trying to create a linux interfaces file out of rows from a database.
in thread Trying to create a linux interfaces file out of rows from a database.

Wow! Fantastic! Works like a charm. I'm humbled by your Perlness. Thanks lots, now I just need to figure out what you did. To get me started could you explain the first line:

push @{$hosts{$row[0]}}, \@row;

I'm just trying to learn on my own & can't find any reference on the web regarding that syntax (I know I'm just not looking in the right places). Again, thanks GrandFather, you gave me a good, healthy bite to chew on.

  • Comment on Re^2: Trying to create a linux interfaces file out of rows from a database.
  • Download Code

Replies are listed 'Best First'.
Re^3: Trying to create a linux interfaces file out of rows from a database.
by GrandFather (Saint) on Jul 14, 2011 at 09:34 UTC

    This first thing to be aware of is than in Perl we make interesting data structures by building them out of either an array or a hash using references to nested arrays or hashes as the values. So your first port of call is to References quick reference to help figure out the syntax for using references. Come back here when you have digested that.

    Ok, now you should be able to figure out that @{$hosts{$row[0]}} dereferences a hash that stores references to arrays as its values. $row[0] is the host name and we are using that as the key to the hosts hash - seems appropriate. The push pushes a reference (that's what the \ in front of @row gives us) to @row (which contains a row of data for a particular interface on a host) into the array associated with the host name. Our %hosts hash is a hash of arrays of arrays!

    To generate the individual host files we iterate over the key values in the %hosts hash and for each key (which is a host name remember) we call genFile passing the host name and a reference to an array containing all the rows we got for the host.

    In genFile we use map {$_->[1]} @$rows; to generate a list of interfaces then use that in the header part of the file. The for loop then creates the entries for each interface.

    True laziness is hard work

      OK, I didn't know how to look up references without knowing they existed! I was doing Google searches for strings like this: '@{$}' & getting nothing back. (Duh!)

      I'm still digesting, but it's much clearer now. I guess this proves that I need to keep hitting the proverbial books. It did seem to me that having just scalars, arrays & hashes to store info was very limiting, but I figured there were workarounds. References seem less like workarounds, and more like shortcuts. Very nice! I'm having a great time learning this stuff, thanks a lot GrandFather!