in reply to Re: adding an element to AoH
in thread adding an element to AoH
Ok, a couple people have responded saying that your version and prasadbabu's solution are exactly the same. They are both right and wrong.
prasadbabu's solution works due to autovivication. As that is a fully documented feature of perl, this should not be taken as a vilification - it's taking advantage of exactly what perl says it will do, and makes it a very perlish solution IMO.
What prasadbabu's solution does not do, however, is fully reinitialise the hashref. If $AoH[0]{heading}[3] doesn't already exist, both methods work just the same. If it does exist, however, the two solutions are widely divergent. I can't even count the number of times I've used your first solution, NetWallah, when I was supposed to use prasadbabu's solution - when I overwrote a structure intending merely to update it. Thus, in my experience, prasadbabu's solution is more often the correct solution.
That said, I often use your latter solution - and find that when I do so, I almost never use it incorrectly. I often claim that code that solves the problem in the domain of the problem rather than the solution is more often correct. This style of pushing into an array is, in my experience, very often exactly how the problem is stated, and since the code matches the problem, it's rarely wrong. It's also hard to get off-by-one errors and the like.
So the question to the OP is: what is your real problem that you're trying to solve? The question seems obvious to me that it's a question in the domain of the solution rather than the domain of the problem. If you're trying to add a new hash to the end of an array, then NetWallah's preferred solution is probably the right one. If you're merely trying to update a specific entry (creating it if it doesn't exist), then prasadbabu's solution is the right one. If you're trying to replace an entry in your array, then NetWallah's first snippet is the right one. I can't really tell which one is the right one - all I can do is point out what each solution's strength is, and it's up to you to decide which one best fits your problem (not solution).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: adding an element to AoH
by jhourcle (Prior) on Jan 05, 2006 at 20:03 UTC |