1

For example

$get = <>;
chomp($get);
$$get = "something";

if user inputted name for $get I want to assign "something" to $name

S0m3oN3
  • 21
  • 4
  • 2
    What you are looking for is a dictionary (called a "hash" in Perl). See [this SO post](http://stackoverflow.com/questions/19923585/how-to-parse-a-key-value-based-dictionary-using-perl) – Arc676 Jan 02 '16 at 08:30
  • 3
    http://perl.plover.com/varvarname.html – Sobrique Jan 02 '16 at 10:17

2 Answers2

6

There are ways to do this, but you really shouldn't. Use a hash instead.

use strict;
use warnings;

my $get = <>;
chomp $get;
my %input;
$input{$get} = "something"; 
friedo
  • 65,762
  • 16
  • 114
  • 184
4

A "hash" (or "dictionary" in some other languages) is like* an array of key-value pairs. This achieves what you describe because you can assign a value to a variable without having a fixed identifier for that variable.

*: Hashes are not arrays.

See this tutorial on Perl101. The following code snippets in this answer are taken from this site.

You can create a hash using the following syntax:

my %stooges = (
    'Moe', 'Howard',
    'Larry', 'Fine',
    'Curly', 'Howard',
    'Iggy', 'Pop',
);

Access and modify values using {}. You can use this syntax to add new values too.

print $stooges{'Iggy'}; #get existing
$stooges{'Iggy'} = 'Ignatowski'; #Overwrite
$stooges{'Shemp'} = 'Howard'; #Set new

You can delete key-value pairs using the delete function.

delete $stooges{'Curly'};

You can get a list of values or keys using the same (key)words:

my @stooge_first_names = keys %stooges;
my @stooge_last_names = values %stooges;
Arc676
  • 4,445
  • 3
  • 28
  • 44
  • 3
    It would be more common to write your hash as a 'fat comma' delimiter of `=>`. Means the same thing, but makes the key-value pairings clearer. – Sobrique Jan 02 '16 at 12:04
  • Well, I was hoping visitors would click the link, as the fat comma style is mentioned there. I wasn't aware it was more common though, – Arc676 Jan 02 '16 at 12:43
  • *"Hashes are not arrays"* why mention arrays in the first place? – Borodin Jan 02 '16 at 13:16
  • @Borodin should I edit to say "list"? That's also a data type in some languages. Or perhaps "group" – Arc676 Jan 02 '16 at 13:18
  • @Arc676: Hmm. It's difficult to think in the mindset where hashes are alien! I personally *hate* the term "associative array" precisely for this reason, and because a standard array "associates" an index with a value so it's really no use at all. In the end I think the idea of a "map" or a "table" represents the idea best, And you can reference [Wikipedia's *hash table*](https://en.wikipedia.org/wiki/Hash_table) entry to do the heavy lifting – Borodin Jan 02 '16 at 14:59