In perl DBI, you can bind a hash element value to a specific column of your query results.
Such that,
as you fetch each row, the hash element value is updated to the current row.
I’m trying to figure out if there’s a way to accomplish that in core perl,
using an hash of (array of arrays).
The end goal is to be able to run something like this:
my $i;
my @a = (
[1,2,3],
[4,5,6],
[7,8,9]
);
my %superhash{'first', 'second', 'third'} = (\$i[0], \$i[1], \$i[2]);
for $i (@a) {
print ${$hash{'first'}} . "\n";
}
I’d love to be able to point $hash{'first'} to the first element in an arrayref, without having to have an array to point to beforehand.
Expected output:
1
4
7
Of course, that code doesn’t work, because there are no elements that $i references to, thus they are undefined.
The tie interface is Perl’s way of making magic variables. In this case, a bit of glob magic needs to be thrown in due to the way the
forloop assigns to its loop variable.which prints
You can also exploit dynamic scope to solve this problem:
which prints