http://www.perlmonks.org?node_id=1015532

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

I am trying to use a loop to create variables such as $line_a, $line_b but use a variable to do that. So if I say: foreach $alpha ( a .. b ) { $line_$alpha = "somenum"; } I get an error. I have tried the dot notation. Is it impossible to use variables within variables? Thanks in advance; Sherman

Replies are listed 'Best First'.
Re: Can I concatenate variables?
by LanX (Saint) on Jan 26, 2013 at 19:58 UTC
    > Is it impossible to use variables within variables?

    Yes, but for good reasons "symbolic references" are deactivated under strict!

    Better use hashes:

    my %line; for my $alpha ( "a" .. "b" ) { $line{$alpha} = "somenum"; }

    If you still insist to use it, search for "variables as variable names perl".

    EDIT: second google hit Why it's stupid to `use a variable as a variable name' from 1998!!! =)

    Cheers Rolf

Re: Can I concatenate variables?
by AnomalousMonk (Archbishop) on Jan 27, 2013 at 00:02 UTC

    ShermW0829: FYI, this
        perldoc -q "use a variable as a variable name"
    gives you the FAQ section to which the reply of Dominus linked by LanX is a counter-blast (well, kinda). (Use single- or double-quotes as appropriate to your OS.)

    Found in C:\strawberry\5.14\perl\lib\pods\perlfaq7.pod How can I use a variable as a variable name? Beginners often think they want to have a variable contain the nam +e of a variable. ...
      Thank you to everyone. I saw the statement that something like PERL people aren't really PERL people until they understand and use hashes. Sherman