The audacity to do such a thing…

121 points

The answer is a map or dictionary.

permalink
report
reply
32 points
*

Or sometimes even just an array. The first time I thought I wanted to do this was 2003 and I was writing a perl script, and I was trying to loop through some sort of array, and write the outputs of some calculations to $val0 $val1 and so on, and I was neck deep into some horrible dark constructs like ${"val" . $i} before I actually realized that I really just wanted an array, you know, like the one I was already using.

It took me forever to understand map (the metafunction).

permalink
report
parent
reply
13 points

It depends. If the variable names are arbitrary, then a map is best. If the variable names are just x_1, x_2, x_3, …, x_n, then a list or dynamic array would be more natural. If n is constant, then a vector or static array is even better.

permalink
report
parent
reply
10 points

I’ve just figured out linked lists and I want to call that the solution ¯_(ツ)_/¯

permalink
report
parent
reply
20 points

When you get a new hammer…

permalink
report
parent
reply
9 points

I mean, I wouldn’t recommend it, but seems like a data structure that could work.

permalink
report
parent
reply
70 points

In python, ‘eval()’ is your friend.

/maliciouscompliance

permalink
report
reply
39 points

locals()[“x”] = 1

permalink
report
parent
reply
3 points
*

Oh god I hate you so much for this. It’s beautiful that it’s possible but I also want you to know you’re instigating cybercrimes.

permalink
report
parent
reply
14 points

Nah, the locals() or globals() object is much better for this.

permalink
report
parent
reply
8 points

In c, nothing and nobody is your friend.

Source: me

permalink
report
parent
reply
4 points

++ is your friend

permalink
report
parent
reply
4 points

Objectively…

permalink
report
parent
reply
4 points
*

# is your worst enemy despite being a copy of a good language

permalink
report
parent
reply
7 points

In Perl, eval can do similar things, but symbolic references are “better” (I’m fairly sure it’s where PHP got the idea, and the syntax, from.) e.g.

$foo = "bar";
$$foo = "potatoes"; # $$foo = access the variable named in $foo, i.e. $bar
print $bar; # prints potatoes

Reading other responses, it seems like Python’s globals object is not entirely dissimilar, especially if you know how Perl deals with symbolic references under the hood.

But just because you can doesn’t mean you should. If you use strict; in Perl, it will fail to compile most of this nonsense. Use a hash / associative array / dictionary / whatever your language (natural and/or programming) calls them instead.

And I’m pretty sure that even without strict, local variables can’t be accessed at all the symbolic way, which is probably for the best. (NB: local is a subtle thing in Perl. By “local” here, I mean the so-called my variables that aren’t accessible outside their scope. local variables are actually localised globals. Enjoy that thought.)

permalink
report
parent
reply
63 points

I distinctly remember asking this question during a 100 level programming class but I just can not remember why I’d ever want to do this?

What problem could I have possibly have been trying to solve where this would seem like the answer.

permalink
report
reply
34 points

A common problem (before learning it is impossible/fraught with danger) is categorisation, like sorting of strings.

Say you have a text, and need to count words of different lengths.

One intuitive approach is to pass through it once and add each word to a list for the corresponding length, as well as making lists as needed. No 7 letter words, no 7-letter-word-list, even though there are longer words.

As humans we’re good at sorting things into an unknown number of categories, and we have to unlearn that for programming

permalink
report
parent
reply
30 points

Would one not just use a dict/hashmap with int keys labelling lengths and the list of strings as the values?

permalink
report
parent
reply
29 points
*

A programmer might, as trained/conditioned by the limits of programming languages.

A human would intuitively not, these are meaningless and/or convoluted concepts to the untrained human.

permalink
report
parent
reply
5 points

Found the Python guy.

permalink
report
parent
reply
6 points

This makes a ton of sense and I think you probably solved this mystery for me.

“Oh I need to iterate over something, and keep track of new information as I do it, therefore I should be able to create ‘dynamic variables’ as I progress.”

permalink
report
parent
reply
0 points

Yep, what you failed to realise at the time is you’ve just invented a dynamic data structure like a list or a dictionary.

permalink
report
parent
reply
14 points

I remember wondering this when I was first trying to self learn. It’s because I needed a map (or list + struct or something) and was such a noob I didn’t know what maps were. Whatever material I was learning from wasn’t good enough, especially for winging things. Plus I was trying to learn C++ and maps aren’t quite so built into the language as they are with a better first language like Python.

permalink
report
parent
reply
13 points

In lower level languages like C/C++ the reason becomes much more apparent when you learn about memory allocation and management (as a bonus it also really helps to understand how OS’s handle memory). Dynamically declaring variables in a loop would mean you need to allocate a chunk of memory for each variable that’s generated on the fly, most of, if not all of the dynamically declared variables would not even use most of their allocated memory resulting in a ton of extra overhead and wasted space within memory. An array is usually the answer when someone asks how to dynamically define variables. With an array you allocate the space needed in memory and can iterate across it block by block resulting in more control and efficiency within your reserved memory block. Linked lists are also a fun thing to look into when you aren’t sure how big your array needs to be. It’s a hard question to answer in a 100 level class because the answer actually goes pretty deep into low level programming, operating system and hardware principles.

permalink
report
parent
reply
4 points

I distinctly remember having the same experience. For some reason I believed dynamic variable naming was a good idea. What was I on??

permalink
report
parent
reply
50 points

Found the creator of PHP

permalink
report
reply
20 points
*
Deleted by creator
permalink
report
parent
reply
9 points

I can’t remember the exact use case but I did submit a PR at a previous job that used $$ and not a single senior developer questioned it

permalink
report
parent
reply
12 points

Piiiitchforks! Getcher pitchforks heeeere!

permalink
report
parent
reply
5 points

Every time we see this in our legacy code we yell out: dolla-dolla bills 'yall!

permalink
report
parent
reply
45 points

The answer is writing a program that writes the variables dynamically to a file and including that file into the source file that uses them.

No need to thank me folks I’m just trying to make the world a better place.

permalink
report
reply
10 points

Or just use a dictionary/hashmap if it’s all in the same program

permalink
report
parent
reply
14 points

Or in JavaScript you can build a string that creates the name of a variable in a sub loop by concatenating ““variable”+$i” and passing that value into a variable that is then read as the name of an incremental variable that a value is then passed to.

This has the advantage of being both extremely unwieldy and highly inscrutable, and there’s a small chance it will make your coworkers send you death threats in slack.

permalink
report
parent
reply
5 points

JavaScript: They were so focused on whether or not they could that they forgot to consider whether or not they should

permalink
report
parent
reply
1 point

I once created a system to automatically load and execute arbitrary JS files and any exported functions in them as part of a server

permalink
report
parent
reply

Programmer Humor

!programmerhumor@lemmy.ml

Create post

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

  • Posts must be relevant to programming, programmers, or computer science.
  • No NSFW content.
  • Jokes must be in good taste. No hate speech, bigotry, etc.

Community stats

  • 3.7K

    Monthly active users

  • 1.5K

    Posts

  • 35K

    Comments