Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Howdy Monks,

I'm trying to get my head around variable interpolation and dereferencing, and all I can say is that I have a headache ;)

Can Perl use the value of one variable as the name of another variable?

For example:

#!/usr/bin/perl -w use strict; my ( @Category, @Cat1, @Cat2, @Cat3, $Sub_Category, $Value ); @Cat1 = qw( a b c ); @Cat2 = qw( 1 2 3 ); @Cat3 = qw( x y z ); @Category = qw( Cat1 Cat2 Cat3 ); foreach $Sub_Category (@Category) { print "$Sub_Category\n"; foreach $Value (@$Sub_Category) { # I'm trying to make Perl see @Cat +1 but, Larry gives me the following error: "Can't use string ("Cat1" +as an ARRAY ref while "strict refs" in use" print "$Value\n"; } } __END__
I apologize for the ambiguous code but, I don't have a real world need for this, I'm just trying to answer questions that sprung up while taking a shower.

Many Thanks!

Replies are listed 'Best First'.
Re: Dynamic Variables?
by dragonchild (Archbishop) on Feb 28, 2002 at 21:46 UTC
    Use multi-level data structures instead. Do something like:
    my %Categories = ( cat1 => [ 'a', 'b', 'c', ], # etc... ); foreach my $sub_category (sort keys %Categories) { print $sub_category, $/; foreach my $value (@{$Categories{$sub_category}}) { print "\t$value\n"; } } __END__

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      dragonchild, thanks! That has the effect I was thinking of.
Re: Dynamic Variables?
by patgas (Friar) on Feb 28, 2002 at 22:07 UTC

    The short answer is, 'yes, Perl can use the value of one variable as the name of another variable', and I realize you're just curious, but dear God don't ever use this in real code. Here's a whole page about it: http://perl.plover.com/varvarname.html

    "We're experiencing some Godzilla-related turbulence..."

      patgas, thanks!

         This is why I love sites like Perl Monks! Instead of getting RTFM, or other newbie blow offs, you all (ok, most) provide thoughtful answers. And best of all, if it's a matter of opinion or TMTOWTDI, you offer reasoning to back it up.