Dynamic variable names: Difference between revisions

From Rosetta Code
Content added Content deleted
(added perl)
Line 30: Line 30:


=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|2.x}}

<lang python>>>> n = raw_input("Enter a variable name: ")
<lang python>>>> n = raw_input("Enter a variable name: ")
Enter a variable name: X
Enter a variable name: X
>>> exec n + " = 42"
>>> exec n + " = 42"
>>> X
42</lang>
{{works with|Python|3.x}}
<lang python>>>> n = input("Enter a variable name: ")
Enter a variable name: X
>>> exec(n + " = 42")
>>> X
>>> X
42</lang>
42</lang>

Revision as of 18:29, 2 June 2009

Task
Dynamic variable names
You are encouraged to solve this task according to the task description, using any language you may know.

Create a variable with a user defined name.

AutoHotkey

<lang AutoHotkey> InputBox, Dynamic, Variable Name %Dynamic% = hello ListVars MsgBox % %dynamic%  ; says hello </lang>

Common Lisp

<lang lisp>

(defmacro set-string (string value) 
 `(setf 
   ,(read-from-string string) 
   ,value))
(set-string "dynamicA" "hello")

(print dynamicA) </lang>

Perl

<lang perl>print "Enter a variable name: "; $varname = <STDIN>; # type in "foo" on standard input chomp($varname); $$varname = 42; # when you try to dereference a string, it will be

               # treated as a "symbolic reference", where they
               # take the string as the name of the variable

print "$foo\n"; # prints "42"</lang>

Python

Works with: Python version 2.x

<lang python>>>> n = raw_input("Enter a variable name: ") Enter a variable name: X >>> exec n + " = 42" >>> X 42</lang>

Works with: Python version 3.x

<lang python>>>> n = input("Enter a variable name: ") Enter a variable name: X >>> exec(n + " = 42") >>> X 42</lang>

Tcl

<lang Tcl>puts "Enter a variable name:" gets stdin varname set $varname 0</lang>