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

I use ‘variables’ with names consisting of a number of characters strings separated by ‘_’.
For example $pear_apple_peach and $pear_damson_orange.
I would like to be able to refer to each character string section of the particular variable I want to use with other variables.
For example if I had three variables called $ch1, $ch2 and $ch3 then when these were
$ch1 = ‘pear’; $ch2 = ‘apple’; $ch3 = peach – I want to use $pear_apple_peach.
I know I can do this with a series of ‘if’ statements but I wondered if there was a more flexible and general way.
For example is there something like $<$ch1_$ch2_$ch3> which would mean I can access the variable ‘defined’ by what is between the ‘< >’ characters OR
something else that would equally do what I want?
  • Comment on Variable access using other variable data

Replies are listed 'Best First'.
Re: Variable access using other variable data
by moritz (Cardinal) on Oct 17, 2010 at 09:44 UTC

    Instead of using variables with variable names, you should use a hash with the former variable names as keys.

    my %fruits = ( pear_apple_peach => 1, pear_damson_orange => 2, ); my @parts = ('pear', 'apple', 'peach'); my $key = join '_', @parts; print $fruits{$key};
    Perl 6 - links to (nearly) everything that is Perl 6.
      Thanks for that very quick reply!
      I use multi-dimensional hashes a great deal, therefore your solution means I just have one more
      ‘dimension’ at the beginning and all may well work as I want. Simple!
Re: Variable access using other variable data
by aquarium (Curate) on Oct 18, 2010 at 00:53 UTC
    using variable contents for variable names is generally frowned upon, with good reason. using multi variable contents to construct a variable name probably not a good idea either.
    A HoHoH structure should suffice, or you could write more general code that could go to any depth by writing the appropriate getter/setter functions to use in the rest of your code.
    maybe the problem can be solved in a different way, which would simplify the inner workings...but there's not enough detail here to make any recommendations in that respect.
    the hardest line to type correctly is: stty erase ^H
Re: Variable access using other variable data
by AnomalousMonk (Archbishop) on Oct 18, 2010 at 00:58 UTC

    A slightly different approach:

    >perl -wMstrict -le "my %fruits = ( pear => { apple => { peach => 'pear_apple_peachy', }, damson => { orange => 'pear_damson_orangish', }, }, ); ;; my ($ch1, $ch2, $ch3) = qw(pear damson orange); ;; print qq{a $ch1-$ch2-$ch3 is $fruits{$ch1}{$ch2}{$ch3}} " a pear-damson-orange is pear_damson_orangish

    See perldsc.