Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
go ahead... be a heretic
 
PerlMonks  

Re^2: conf file in Perl syntax

by Ravendark (Acolyte)
on Jun 11, 2009 at 11:25 UTC ( #770608=note: print w/ replies, xml ) Need Help??


in reply to Re: conf file in Perl syntax
in thread conf file in Perl syntax

Thanks LanX for your reply. I am new guy in perl, but I installed the IniFiles module. what you are writing is hard-to-read syntax for me. What I need is a little code snippet that does the following: I have the inifile:

[hosts] # hostname = IP host_1 = 192.168.1.1 host_2 = 192.168.1.2 host_3 = 192.168.1.3
The only thing I need is a little piece of code that will get all the hostnames into an array @hostnames and all the IPs into an array @ips. Is this possible? Thank you!


Comment on Re^2: conf file in Perl syntax
Download Code
Re^3: conf file in Perl syntax
by Anonymous Monk on Jun 11, 2009 at 12:34 UTC
    $ cat hosts.conf
    <Hosts>
    host_1 = 192.168.1.1
    host_2 = 192.168.1.2
    host_3 = 192.168.1.3
    </Hosts>

    $ cat hosts.pl

    #!/usr/local/bin/perl -w
    use Config::General(ParseConfig);
    $configFile='hosts.conf';
    my %config = ParseConfig($configFile);
    foreach my $host (keys(%{$config{Hosts}}))
    {
    print "Machine : $host => $config{Hosts}{$host}\n";
    }

    $ ./hosts.pl
    Machine : host_1 => 192.168.1.1
    Machine : host_2 => 192.168.1.2
    Machine : host_3 => 192.168.1.3
Re^3: conf file in Perl syntax
by GrandFather (Cardinal) on Jun 11, 2009 at 21:11 UTC

    Don't do that (parallel arrays). Either use an array of arrays (AoA):

    my @IPMap = ( [ "host_1", "192.168.1.1" ], [ "host_2", "192.168.1.2" ], [ "host_3", "192.168.1.3" ], );

    or better, a hash:

    my %IPMap = ( host_1 => "192.168.1.1", host_2 => "192.168.1.2", host_3 => "192.168.1.3", );

    YAML allows both structures to be generated directly from the configuration file. For example:

    use strict; use warnings; use Data::Dump::Streamer; use YAML (); my $yamlStr = <<END_YAML; --- host_1: "192.168.1.1" host_2: "192.168.1.2" host_3: "192.168.1.3" --- - - host_1 - "192.168.1.1" - - host_2 - "192.168.1.2" - - host_3 - "192.168.1.3" END_YAML my ($IPMapH, $IPMapAoA) = YAML::Load ($yamlStr); Dump $IPMapH; Dump $IPMapAoA;

    Prints:

    $HASH1 = { host_1 => '192.168.1.1', host_2 => '192.168.1.2', host_3 => '192.168.1.3' }; $ARRAY1 = [ [ 'host_1', '192.168.1.1' ], [ 'host_2', '192.168.1.2' ], [ 'host_3', '192.168.1.3' ] ];

    True laziness is hard work

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (10)
As of 2014-04-21 16:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (497 votes), past polls