Paul Lalli said:
No you don't. First read
perldoc -q "variable name"
and then search Google for the absurdly large number of posts dealing
with "variable as a variable name" and "symrefs", including more than a
few in the last week.
Yes, I am painfully aware of the gazillion questions along those lines.
Notice I said "like", meaning, what is the correct way of doing this.
Why would you want to loop through the *names* of the arrays instead of
the arrays themselves?
Because I wanted to use the array name along with its data.
Because you've ill-defined your problem. This is basically an XY issue.
You have issue X, which is that you want to access each array one at a
time. You've decided the solution to that is Y, to loop through the
names of the arrays. Your method for Y doesn't work, so you're trying
to figure out a different way of doing Y, instead of figuring out the
proper way of doing X.
Quite likely true (see below).
In the general case, loop through the arrays themselves instead of the
array names:
foreach my $arr (\@array1, \@array2, \@array3) {
foreach my $row (@$arr) {
print "$row\n";
}
}
OK, that shows me how to use hard references correctly. Thank you.
HOWEVER, in this case all you're doing is printing each element of each
array, followed by a newline. Why even bother looping?
{
local $, = "\n";
print @array1, @array2, @array3;
}
print "\n";
Now that's a useful piece of code, however let me wind the clock right back
and explain what I'm trying to do, ie: X.
I'm reading in a fields from a text file to be loaded into a database.
There are various sets of data that can have 1-6 lines of information. For
example
Address1=1 fred st
Address2=suburb
Address3=city
In the database, there are 6 columns defined for the Address, so what I need
to do is read in the addresses (and ensure that I account for records with
less than 6 lines). Now there are at least 6 other data types like this.
What I'm currently doing is
foreach my $i (0..5) {
push @insert_record,$addresses[$i];
}
foreach my $i (0..5) {
push @insert_record,$elements[$i];
}
and so on, to build up an array used to insert a record into the database.
Using repeated code like that is a red warning sign saying that it can be
compacted, however I wasn't (still aren't) sure of the best way of handling
it.
Note that the loop is needed to pad out the insert_record array with undef
values if the array being referenced is less than 6 elements. This ensures
that the fields match those defined in the database.
Hopefully that explains things a little better.