in reply to How can I use the value of a scalar as the name of an array variable?

What you're looking for are symbolic (or as Russ called them, soft) references.
my( @fruit, @meat, @dairy ); while (<>) { chomp; my( $category, $item ) = split /\t/; push @{$category}, $item if defined @$category; }
Note that this version would only push items with pre-declared categories, the rest would be silently discarded -- this might be the behaviour you want, it might not. Your call.

Update: fixed test per chipmunk's reply.

  • Comment on Re: Can I determine if the value of a variable is the same as an arrays name?
  • Download Code

Replies are listed 'Best First'.
Re: Answer: Can I determine if the value of a variable is the same as an arrays name?
by Fastolfe (Vicar) on Nov 30, 2000 at 20:33 UTC
    The big problem with soft references is that they make things very difficult to debug, and if the user has any control of the variable name, they can cause all sorts of horrible things to happen. What if your program (by accident in your code, by design of somebody malicious, or by the seemingly innocuous mistake of a user) ended up trying to make changes to a variable named "/"? $/ has a certain meaning that can cause your script to behave strangely. All of the sudden your files aren't being read normally.

    Try debugging THAT!

    Generally most uses of variables with soft references can be done much more cleanly by using hashes.

Re: Answer: Can I determine if the value of a variable is the same as an arrays name?
by chipmunk (Parson) on Nov 30, 2000 at 20:52 UTC
    Quote:
        push(@{$category}, $item) if (@{$category});
    ...
        Note that this version would only push items with pre-declared categories, the rest would be silently discarded

    I'm afraid that version will silently discard everything. @{$category} will never be true, because all of your pre-declared arrays start with zero elements.

    You could do something like this:

    @fruit = (undef); @meat = (undef); @dairy = (undef); while (<FOOD>) { chomp; ($category, $item) = split(' ', $_); push(@{$category}, $item) if (defined @{$category}); } shift @fruit; shift @meat; shift @dairy;
    But really, why would you want to? I think it's much simpler to restrict the categories if you use a hash of lists.