Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Calling a variable value as a variable

by davido (Cardinal)
on Dec 13, 2018 at 00:13 UTC ( #1227190=note: print w/replies, xml ) Need Help??

in reply to Calling a variable value as a variable

Symbolic references are absolutely the wrong way to go about the problem you are trying to solve, as are global variables. Read perlintro and you will learn about hashes (which you are already using but seem to not be using in all the places you should). Perl's symbol tables internally are implemented using hashes. If it works for Perl, it's certainly going to be good enough for you too. But even though it's a terrible use case, referring to variables using a variable is possible:

$red = 1; $blue = 2; $green = 3; foreach $color (qw(red blue green)) { print "$color: $$color\n"; }

But this is dangerous, bug prone, broken by design. Anywhere you feel you need to name a variable programatically, you need either a hash, an array, or a hard reference, which you can read about in perlref and perlreftut. Hashes and arrays are discussed in perlintro and perldata. Putting it all together is discussed in perldsc, perllol.

Someone already linked to MJD's venerable trilogy of Usenet posts about why it's stupid to use a variable as a variable name. He was right 20 years ago when he posted that, and is still right. The road you are going down leads to unsolvable bugs that can only be fixed by complete rewrite.

perlsub will discuss lexical variables. strict and warnings will discuss how to put the brakes on some forms of truly awful design decisions.

Please take a few hours now learning to do it right rather than succumbing to the allure of getting it done quickly with limited understanding. Doing it right will be better for you in the longrun.

There are legitimate uses for symbolic references. Those uses are very limited, and very narrow where they should be applied. Those uses should live buried deep in utility modules with nice clean user interfaces. Nobody should ever see them. If symbolic refs didn't even exist in Perl you, the happy programmer, would almost never even notice their absence.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1227190]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2019-06-25 17:42 GMT
Find Nodes?
    Voting Booth?
    Is there a future for codeless software?

    Results (107 votes). Check out past polls.