Your skill will accomplish what the force of many cannot |
|
PerlMonks |
Splitting a hashref into hashrefsby legLess (Hermit) |
on Mar 20, 2003 at 03:44 UTC ( [id://244526]=perlquestion: print w/replies, xml ) | Need Help?? |
legLess has asked for the wisdom of the Perl Monks concerning the following question:
Monks ~
I'm struggling with the very laudable goal of making my HTML templates as easy to use as possible, and hoping I can learn some new Perlery while I'm at it. I'm using Slash and Template Toolkit, but I think the Slash methods are clear enough so no knowledge of it is needed to understand the code (yeah, that surprised me too once I started hacking it :). My solution below works, but strikes me as ugly. The Problem I'm getting a hashref (cunningly named '$hashref' for your reading pleasure) back from a database:...with the hope of passing it roughly like this (where '$org' and '$group" are hashrefs): ...into this template:
First attempt: splitting hashrefs in the database return I tried a few ways of doing this in the database call, but I confess that my Perl wasn't up the the task. I was hoping to pass the data to two hashrefs (e.g. $orgs and $groups) but I couldn't figure out how to slice up the returned hashref into two new hashrefs. Doing it in the database call would also allow me write the SELECT part of the query as written above rather than what follows, which is what I've used to prevent key collisions in the hashref:
An arrayref won't work I could get an arrayref from the database -- these are easy to split -- but that would mean using (e.g.) [% org.1 %] in the template, which isn't very readable and breaks when the field order changes.One hashref won't work I could also pass the hashref directly to the template:...which is simple in the code but would mean this in the template:
What worked In the end I came up with this: constructing an anonymous hashref and passing it to the template. It gives me total control of the named parameters I pass to the template and ensures that the HTML guy (also me :) has the easiest experience possible.The only thing I don't like is that while the template has been cleaned up the code is much gnarlier. On balance I think this is a good trade-off, but I wonder if my ignorance is setting up a false dichotomy. Is there a less gnarly way of doing this (or at least a way with less typing)? -- Man With No Legs, Inc.
Back to
Seekers of Perl Wisdom
|
|