Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to name an array with the name of the variable

Status
Not open for further replies.

user2base

Technical User
Oct 16, 2002
29
GB
I want to create an array whose name is the name of a scalar.
For instance, if I have:
$name = "arrayname";
I want to use $name to name my array rather than call it @arrayname.

It looks strange but it makes sense in my context as the value of the scalar $name will vary in a loop.

I have tried @\$name but it does not work.

Is it possible to do that ??

U.

 
Code:
#!perl
$str = 'car';
@$str = ('vw','blue','GTI','hatch-back');

foreach (@car) { print "$_\n"; }
'hope this helps

If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
 
You may have to look into using
Code:
eval();

Create the string containing the PERL commands
you need and then
Code:
eval();
the string...
 
Sorry if my title was not descriptive enough.

Thanks for your answer but actually what I want to do is the opposite.

To simplify let's assume that for each key in a loop I want to create an array named "the value of that key".
The problem is that I don't have these values hardcoded like ('vw','blue','GTI','hatch-back') but there are dynamically created from a hash.

So I will have something like this:
for each $key (keys %hash)
push $key in an array called $hash {$key}


 
wow this is an old post, but I thought I should comment since I had the same problem/request.

goBoating had the right idea.

in my case, I have a number of data files that are the result of feedback forms. Each element of data is categorized, and I need to compile the results.
Instead of making 11ty billion arrays to collect the results for each field, and then list that many if statements (i.e. if line contains submittedBy { push @submittedBy, $data } ) - I wanted to automatically create the correct array and populate it (that way you don't actually need to know the data fields at all or how many).

goBoating's syntax worked well

I split the line using RE into $bin = field and $data = user input.
then "push @$bin,$data;"

this created and corectly populated all the arrays I needed.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top