0

how can i define scalar variables in perl out of values stored in an array. Let's say i have an array like this:

my @parameter_list = ("admin_name", "admin_pass", "customer_id", "email", "domains", "subdomains", "aliases", "emails", "ftps", "sqldbs", "sqlusers", "space");

Out of this array i want create scalar variables with this code. I couldn't figure out how to do it:

foreach (@parameter_list) { my \$("test"); }
4
  • 3
    Official response to XY problem is why you would like to do such thing. Commented Jan 29, 2015 at 10:14
  • I can reuse this list of parameters again in another place in the code, instead or rewriting it again. Commented Jan 29, 2015 at 10:20
  • 1
    sounds like you need to put them in a hash, then you can call them by name. Commented Jan 29, 2015 at 10:40
  • Ok , hash would be also fine. Can you provide me an example. Commented Jan 29, 2015 at 10:50

1 Answer 1

4

It sounds like you want to be able to call variables by names in the array. You can create a hash which allows you to access a list by name rather than by index. Below code shows how you can create a hash from the array of parameter names.

use strict;
use warnings;

my @parameter_list = ("admin_name", "admin_pass", "customer_id", "email", "domains", "subdomains", "aliases", "emails", "ftps", "sqldbs", "sqlusers", "space");
my %parameters;

foreach my $parameter ( @parameter_list ){
        $parameters{$parameter} = undef;
}

$parameters{'admin_name'}='scott';
$parameters{'admin_pass'}='tiger';

print "DB login: $parameters{'admin_name'}/$parameters{'admin_pass'}\n";

OUTPUT

DB login: scott/tiger

This will create a hash with parameter names with no values set. You can then set values either by giving the parameter name, similarly you can access the value of the variable by giving it the name of the parameter.

there are other ways you can do this with things like map but i have left them out to keep it simple.

Hopefully this solves your issue is it wasnt quite clear in the question what you were trying to achieve.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.