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 Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use variable to represent an array name

Status
Not open for further replies.

waiterm

Programmer
May 17, 2004
236
GB
My business partner just asked the following, and I'm not sure about how to do it:

Is there a way of using a variable to represent an array name...?? i.e.

Code:
$var = @ARRAY (the name of the array not the value)
foreach $whatever(@[$var])  { . . . .. }

I thought there was some way of doing it using the $ symbol in front of the array name i.e. $var = $@array, basically he wants to load the array name dynamically in the foreach loop if that makes sense.

Thanks in advance.

Rob Waite
 
Hi Rob,

You mean like this?

$var = 'an_array';

$$var[0]='first';

print @an_array[0];


Mike

To err is human,
but to really foul things up -
you require a man Mike.

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

 
Yes there is, though it's usually a bad idea. Here's a good overview of why it's bad.

If your arrays are related, you're better off storing them in the same data structre (probably a hash in this case). For example, where you create the array, you can change it to this:
Code:
# old code
# my @foo = ( 0 .. 10 );

# new code
my %hash_of_arrays;
my $var = 'foo';
@{ $hash_of_arrays{$var} ) = ( 1 .. 10 );

Then to dynamically use an array in the foreach loop:
Code:
foreach $whatever ( @{ $hash_of_arrays{ $var } } ) {
  # . . . .
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top