Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: define variable name on the way

by amon (Scribe)
on Apr 27, 2014 at 18:10 UTC ( [id://1084015]=note: print w/replies, xml ) Need Help??


in reply to define variable name on the way

There is a feature similar to this in Perl, but this is considered to be a very bad idea, because it makes code utterly unmaintainable. Use arrays instead.

my $index = 0; my @array; $array[0] = "hello"; $array[1] = "world"; print "$names[0] $names[1]"; #=> "hello world"

You can also use variables for the 0 or 1: “my $index = 0; $array[$index] = "hello"

Or you could use hashes

my $index = 0; my %hash; $hash{greeting} = "hello"; $hash{name} = "world"; print "$hash{greeting} $hash{name}"; #=> "hello world"

Again, you could also use variables:

my $key = "greeting"; $hash{$key} = "hello";

Edit: properly escaped square brackets

Replies are listed 'Best First'.
Re^2: define variable name on the way
by amon (Scribe) on Apr 27, 2014 at 18:13 UTC

    The canonical explanation why you shouldn't use variables as variable names was given by MJD in the varvarname emails.

Re^2: define variable name on the way
by amon (Scribe) on Apr 27, 2014 at 18:15 UTC

    Also, the above formatting got b0rked. The second paragraph should be:

    You can also use variables for the 0 or 1: “my $index = 0; $array[$index] = "hello"

      Because you posted as a registered user, you can un-b0rk your own original post by editing it, in this case by adding  <code> ... </code> tags. Please see Writeup Formatting Tips and Markup in the Monastery.

      Update: If you edit or update one of your posts, please add a brief notation of the edit and its nature.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-20 06:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found