in reply to Re: use simple scalar names to point to specific array elements
in thread use simple scalar names to point to specific array elements

I have to read in a whole host of columns from a data base. I want the variable names to be the same as the column names (for readability and maintainability).

I was trying to create only one list within the code with all these column names defined. Then, if someone needs to enter a new column, appending to the list could then be used to create the proper 'SELECT' statement, and also modify the way the result was read.

i.e. What I don't want:

my $query = "SELECT abc def ghi jkl ....."; ... set up database stuff ... ($abc, $def, $ghi, $jkl ...) = @array;
because then the next guy to maintain my code might goof up when they have to add (or move around) columns.

So I set up an array with all the column names, and create the query (which is complex) using the column names.

So far so good, I got that far. But now when I want to be able to create a list (or array) that can read in the result, and create new variables based on the list of columns.

So, I decided to make things difficult for myself, and was fartin' around trying to construct some code that could use the pre-existing list of column names to construct the array assignment.

Something like (I haven't tried this, i'm just trying to brain storm...)

map {$_='$'.$_} (@var_list=@col_list) join (",",@var_list); (eval "$var_list") = @array;
I'm guessing that "use strict vars" is going to be upset when I try to access $abc;

However, before I started with that, I just sorta fell back into some of the joys of FORTRAN (yes fortran can be fun too).

In my previous fortran code, one could read a line from a text file, using a single string or array. Then, use the individual fields as required. If the format of the input line changed, the only thing that needs to be changed is the equivalence statement.

Any thoughts?

I could always just hard code the variable and column names and be done with it, but I don't wanna. I can be very stubborn at times.

Replies are listed 'Best First'.
Re: Re: Re: use simple scalar names to point to specific array elements
by diotalevi (Canon) on Dec 05, 2003 at 21:14 UTC
    Oh ick. Use a hash and read "Why it's stupid to `use a variable as a variable name" Part 1, 2, 3. You're in the same ballpark as symbolic references (except worse because you are using eval).
      Of course it's an 'ick'. That's why I came to perl monks for some help brainstorming for further ideas.

      I really don't want to write code that does not compile under 'use strict', because even I can make mistakes sometimes.

      I shall think upon hashes, and come up with something that will work (anything is possible given enough time and determinination)

      Sandy