[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: perl + Konfigurationsdatei



Hallo Kai,

Kai Wilke schrieb:
Hallo allerseits,

ich habe ein Problem mit Perl und kenne mich auch nicht in Perl aus.
Ich möchte das ein gefundenes Perl-Script die Variablen aus einer
Konfigurationsdatei einliest und nicht im Script definiert sind.

Nun habe ich nat. gegoogelt und auch das Perl-Kochbuch gefunden.

online?

Ich habe aber irgendwie ein Verständnis-Problem, bei dem Thema.
Jedenfalls funktionieren die Beispiele bei mir nicht so richtig (vllt.
zu blöd).

-----------------------cut----------------------------
Perl Code:
### Globals - you can change these as needed
my $conf_file = "/etc/kwtools/kwdjbdns-update.conf";

### reads the configuration file & makes a hash of what's in there.
sub read_conf_file {

  unless (open(CONFFILE,$conf_file)) {
	#`logger -t dns_update error opening configuration file`;
	print STDERR "Can't open configuration file\n";
	exit 1;
  }
  while (<CONFFILE>) {
	  chomp;
	  s/#.*//;
	  s/^\$+//;
	  s/\s+$//;
	  next unless length;
	  my ($var, $value) = split(/\$*=\$*/, $_, 2);
	  print "$var";
	  print "$value";
  }
  close CONFFILE;
}

&read_conf_file;

-----------------------cut----------------------------
Nun kann ich zwar die Konfigurationsdatei einlesen und auch mittels
"print" ausgeben aber nicht auswerten, bzw. Variablen belegen.

dieser Codeschnipsel liest die Datei ein und gibt diese Werte aus - mehr
nicht. Wenn du die Werte als Rückgabewerte der Subroutine haben willst, dann
musst du statt der beiden print-Anweisungen die key/Value-Paare in einen hash
aufnehmen.

also z.B. so:


### reads the configuration file & makes a hash of what's in there.
sub read_conf_file {

  my %data = ();

  unless (open(CONFFILE,$conf_file)) {
	#`logger -t dns_update error opening configuration file`;
	print STDERR "Can't open configuration file\n";
	exit 1;
  }
  while (<CONFFILE>) {
	  chomp;
	  s/#.*//;
	  s/^\$+//;
	  s/\s+$//;
	  next unless length;
	  my ($var, $value) = split(/\$*=\$*/, $_, 2);
	  $data{$var} = $value;
  }
  close CONFFILE;

  return %data;
}

my %meine_daten = &read_conf_file;

# zur Kontrolle den Hash ausgeben
foreach my $key (keys %meine_daten) {
  print $key, ' ', $meine_daten{$key}, "\n";
}

Mit freundlichen Grüßen
Hans-Dietrich








Reply to: