in reply to Parsing a config file

Hi there,

This code is a bit convoluted.

while (my @X=<CFGFILE>) { foreach $_(@X) { next unless /^\w/i; push (@server, $_); ($machine, $default, $type, $connect)=split(/,/,$_); print "$machine, $default, $type, $connect"; } }
@X=<CFGFILE> will slurp the file into @X in one go so your while is not looping. I would suggest something like this instead:
while (<CFGFILE>) { # read each line in turn to $_ next unless /^\w/i; push (@server, $_); # do you realy want this array too ? ($machine, $default, $type, $connect)=split(/,/,$_); print "$machine, $default, $type, $connect"; } }

Depending on what you do with the data after you have read it you may find something like a hash of arrays or hash of hashes a nice way to store it

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %servers_HoA; my %servers_HoH; while (<DATA>) { # read each line in turn to $_ next unless /^\w/i; my ($machine, $default, $type, $connect)=split(/,/,$_); print "$machine, $default, $type, $connect"; $servers_HoA{$machine}=[$default, $type, $connect]; # or perhaps $servers_HoH{$machine}{default} = $default; $servers_HoH{$machine}{type} = $type; $servers_HoH{$machine}{connect} = $connect; } print "Hash of Arrays\n"; print Dumper(\%servers_HoA); print "\nHash of Hashes\n"; print Dumper(\%servers_HoH); __DATA__ printserver1,default,cups,cups printserver2,no,aix,rsh
And here is the output of that last bit of code
printserver1, default, cups, cups printserver2, no, aix, rsh Hash of Arrays $VAR1 = { 'printserver1' => [ 'default', 'cups', 'cups ' ], 'printserver2' => [ 'no', 'aix', 'rsh ' ] }; Hash of Hashes $VAR1 = { 'printserver1' => { 'type' => 'cups', 'default' => 'default', 'connect' => 'cups ' }, 'printserver2' => { 'type' => 'aix', 'default' => 'no', 'connect' => 'rsh ' } };

Cheers,
R.

Pereant, qui ante nos nostra dixerunt!

Replies are listed 'Best First'.
Re^2: Parsing a config file
by tcf03 (Deacon) on Mar 10, 2005 at 17:09 UTC
    OK moving further along this vein:
    #!/usr/bin/perl -w use strict; use diagnostics; use Data::Dumper; my $config="/var/www/cgi-bin/prt.cfg"; open (CFGFILE,$config) || die "unable to open $config: $!\n"; my (@server,@arrayref); foreach $_(<CFGFILE>) { chomp; next unless /^\w/; @server=split(/,/,$_); push (@arrayref, [ @server ]); } print "servers: $arrayref[0][2]";
    what if I want to call all servers?
    ie print "servers: $arrayref[0 ... $#arrayref][0]
    I know that wont work, but it best explains what I want to do...

      you need to loop through the array holding the refs and de-ref the bits you want to print...

      print "$_->[0]\n" for @arrayrefs # or map may be your friend print "servers: ", (join ", ", map {$_->[0]} @arrayrefs), "\n";
      BTW you can also get rid of the intermediate array @servers by just throwing split straight into an anonymous array
      push @arrayrefs, [split(/,/,$_)];

      Cheers,
      R.

      Pereant, qui ante nos nostra dixerunt!