in reply to How can I use the value of a scalar as the name of an array variable?
You can do this using symbolic references, but running under -w or use strict this will often generate a number of warnings.
Here's an example:
$two = 'test'; @three = ('test'); my @array = ('one', 'two', 'three'); foreach (@array) { if (@$_) { print "Array exists: $_\n"; } if ($$_) { print "Scalar exists: $_\n"; } }
And this is how it would apply to your problem:
my @fruit = (); my @meat = (); my @dairy = (); open (FOOD, "./food.txt") while (<FOOD>) { chomp; ($category, $item) = split(/\$/, $_); push(@{$category}, $item) if (@{$category}); }
So yes, it's do-able, but it's not always the best programming method although it seems to fit here and wouldn't generate warnings as you've declard the arrays you're trying to assign to and not initializing them on the fly.
Originally posted as a Categorized Answer.
|
|---|