in reply to Combining 2 variable?

There is nothing elegant, or smart about doing this, but because we're playing with Perl, it is possible:

$a[3] = "Hello"; $b = 'a'; $c = '[3]'; $d = eval "\$$b$c"; print "$d\n";

Output: Hello. Hopefully the fact that this violates strict 'refs', strict 'vars', and requires string eval should be enough warning flags to dissuade using the construct.

Here's how it works. First, we assign a value to $a[3]. Then we construct a string that looks like "$a[3]" using a component that looks like "a", and a component that looks like [3]. Then we evaluate that string as if it were code. The code is an expression returning the value stored in @a's fourth element.


Dave

Replies are listed 'Best First'.
Re^2: Combining 2 variable?
by LanX (Saint) on Sep 01, 2014 at 00:30 UTC
    > this violates strict 'refs', strict 'vars',

    To be precise: eval doesn't violate strict 'refs' and strict 'vars' is easily calmed with my declarations ( though the OP never used strict )...

    > perl use strict; use warnings; my @a; $a[3] = "Hello"; my $b = 'a'; my $c = '[3]'; my $d = eval "\$$b$c"; print "$d\n"; __END__ Hello

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)