Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: variable with $$

by bart (Canon)
on Apr 08, 2004 at 10:56 UTC ( #343572=note: print w/replies, xml ) Need Help??


in reply to variable with $$

You're asking for symbolic references, huh? At least, I think you are. Well: don't do it, unless you know really well what you're doing — and basically, if you have to ask how to do it, I dare to bet that you don't. Making a name based on a user's input is always very dangerous. You never know whether he'll input the name of a variable you've used yourself in your program.

See dominus' classic 3 articles on his website, for more arguments against it:

  1. Why it's stupid to `use a variable as a variable name'
  2. A More Direct Explanation of the Problem
  3. What if I'm Really Careful?

In general: don't do it. Use a hash. Like this:

my %v; # my hash for user variables $v{Sam}++; # or: my $name = 'Sam'; $v{$name}++;

Oh, and if you really want to do it, try $$name or ${$name}, which both do the same thing, and only work on global (= package) variables — and only with no strict 'refs'. Just to show you it can be done... ;-)

If all you want is to work on predefined variables with no input from the user/outside world, try hard references instead.

my $var = \$sam; $$var++; # increments $sam
Yes, the syntax is exactly the same. That's one reason why coding without strict 'refs' in place, is a rather bad idea.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://343572]
help
Chatterbox?
[shmem]: LanX: ah, that one. You'll get the bug reports also :P
[Discipulus]: upvote me! i'll make pm great again! ;=)
[shmem]: Discipulus reminds me of an irish saying: "I would guess a tomorrow can wait 'til this day is done" :-)
[LanX]: nite! :)
[Discipulus]: or a spanish one: ' qui mucho se despide no quiere despedirse'
shmem slides into the envelope
[shmem]: Discipulus *quien*

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2017-04-29 22:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I'm a fool:











    Results (534 votes). Check out past polls.