perlknight has asked for the wisdom of the Perl Monks concerning the following question:

I have a config file in the form of @<hostname>, e.g: @host1, @host2:
@<hostname> =( {a => value1, b => value }, {a => value, {b=>value} )
the script calls require on the config file. how would I declare a dynamic array variable on the script, cuz I only need one of the array variable. Obviously this is done so that I don't have to keep track of the config files on every host which I am pusing the the scirpt out to. Thanks.

Replies are listed 'Best First'.
Re: dynamically generated array variable
by Tanktalus (Canon) on Jan 02, 2007 at 20:39 UTC

    Can you convert the config file to be of the form:

    $config{<hostname>} = [ {a => value1, b => value }, {a => value, {b=>v +alue} ]
    %config = ( <hostname> => [ {a => value1, b => value }, {a => value, {b=>value} + ] );
    instead? It'll be much simpler to handle this way... it'll also be easier to handle FQDNs, too, if ever needed (just put the hostnames in quotes).

Re: dynamically generated array variable
by ikegami (Patriarch) on Jan 02, 2007 at 20:36 UTC

    Your config file parser simply creates those variables instead of allowing to query them? To work with this bad design, you'll need to use symbolic references.

    my $hostname = 'hosta'; my @host = do { no strict 'refs'; @$hostname };

    Or if a reference is fine:

    my $hostname = 'hosta'; my $host = do { no strict 'refs'; \@$hostname };

    Update: I forgot to mention the above only works if @hosta is a package variable, not a my variable.

      I did this and it works:
      #use strict; $host = qw(@hosta); foreach $cnf (eval($host) { }
      . is there a way to specify it so that I can use strict? Thanks.

        Yes. I already provided that. use strict does not give an error with the code in my previous post.

        use strict; use warnings; # ... Load config file ... my $hostname = 'hosta'; my @host = do { no strict 'refs'; @$hostname }; foreach my $cnf (@host) { ... }

        By the way, why are you using qw(...) to initialize a scalar. Don't you want
        $host = q(...);
        or the equivalent but more readable
        $host = '...';

Re: dynamically generated array variable
by Shade (Novice) on Jan 02, 2007 at 22:46 UTC
    The following works, with some modification to your original array:
    use strict; use warnings; my @host1 =( {"a" => 1, "b" => "two" }, {"a" => 3, "b" => "four"} ); foreach my $hash (@host1) { print "a = " . ${$hash}{"a"} . ", b = " . ${$hash}{"b"} . "\n"; }