It doesn't matter. Hash keys are stored internally only once, even if they are used across multiple hashes. So though it may seem wasteful to have two hashes with the same key in them, it's not. The same goes for multiple rows of anonymous hashes with the same keys. This is an internal, automatic, and invisible optimization, but a smart one at that.
Update: For the record and posterity, I wanted to mention that this optimization is known as "Shared strings", and is discussed in Advanced Perl Programming (the Cougar book), published by O'Reilly & Associates. Find it in Chapter 20: Perl Internals, Section 3.3.1. The exact quote is:
To prevent unnecessary duplication, the actual key strings are maintained in a systemwide shared string table (strtab in strtab.h). strtab is a simplified HV: each value here keeps a reference count of the number of uses of that string.
It's also discussed in http://www.faqs.org/docs/perl5int, where Simon Cozens writes the following in section 4.2.2.2:
The HEK stored inside a hash entry represents the key: it contains the hash value and the key itself. It's stored separately so that Perl can share identical keys between different hashes - this saves memory and also saves time calcu.llating the hash value.
Neither of those sources are as ubiquitous as a POD reference, but aside from unraveling the source, they seem to be the best insight we've got on the topic.
| [reply] |
| [reply] |
How are keys unecessary to a hash??? Maybe you want something like:
...
$sth->execute(...) or die(...);
my %field_idx = do {
my $i = 0;
map { $_ => $i++ } @{$sth->{NAMES}}
};
my $row;
while ($row = $sth->fetch()) {
print($row->[$field_idx{'userid' }], $/);
print($row->[$field_idx{'password'}], $/);
}
...
| [reply] [d/l] |
| [reply] |
I'm not exactly sure what you're asking about, perhaps you could give an example. If what you want is just the values without the keys, that would be an AoA and is obtainable from the database with selectall_arrayref(). If you want each row keyed to a given column, that is an HoH, obtainable with selectall_hashref(). If you want an array of hashrefs for each row, that is an AoH and obtainable with selectall_arrayref(...Slice=>{}). If you want to be able to refer to the results of a database fetch by name without populating a hash, you can predefine a set of variables and populate them with bind_cols. But perhaps you're asking about something else? | [reply] |