1: # What makes this one better? nothing really. i tried out
2: # App::Config, but (according to my understanding) one needs
3: # to state all variables in the configuration before reading
4: # in the configuration file. That's useful in some situations,
5: # i just didn't like it. i tried Config::IniFile which worked
6: # alright, but being lazy i don't like a function call in
7: # between me and my values (i could also tie a hash to it,
8: # which is useful, but i had a couple minutes so i thought i'd
9: # do a quick reinvention of the wheel)
10: #
11: # What makes mine different is that it's a quick and dirty parser
12: # that floods the packages namespace (not main's) with the
13: # variables. It doesn't handle arrays or hashes (to be handled
14: # at a later date) just simple name=val (with any number of
15: # spaces).
16: #
17: # The way to call it (in case you're interested) is just:
18: #
19: # use ConfFile("conf/file/name_here");
20: #
21: # this seems elegant and useful because i can put in one line
22: # at the top of my code and use all of my configuration
23: # variables. It just makes sense to me for some reason.
24: # Anyway, enough banter, here it is...
25:
26: #!/usr/local/bin/perl -w
27:
28: package ConfFile;
29: use strict;
30: use Carp;
31:
32: sub import {
33: shift; # this gets rid of the calling package...
34: my ($call) = caller;
35:
36: # i also changed this: why die cuz there was no file?
37: my $filename = $_[0] || return;
38: my $symbols = &readFile;
39:
40: carp "No values were read in from $filename.\n" unless (keys %$symbols);
41:
42: # one has to turn off strict 'refs' in order to flood the namespace of
43: # the calling package in this way.
44: no strict qw(refs);
45: foreach (keys %$symbols) {
46: *{"${call}::${_}"} = \$symbols->{$_};
47: }
48: use strict qw(refs);
49:
50: return;
51: }
52:
53: sub readFile {
54: my $file = shift;
55: my (%sym, $key, $val);
56: local $_;
57:
58: open FILE, $file or croak "Couldn't open file $file: $!";
59:
60: while (<FILE>) {
61: next if /^\s*#|;/;
62: next if /^$/;
63: chomp;
64:
65: ($key, $val) = /^\s*?(\S+)\s*?=?\s*?(\S+)$/;
66: $sym{$key} = $val;
67: }
68: close FILE;
69:
70: return (keys %sym) ? \%sym : undef;
71: }
72:
73:
74: 1;
75:
76: # please, please comment on anything done badly, i do hope
77: # to use this someday soon...
78: #
79: # jynx
80: #
81: # Update: i used Fastolfe's suggestions so this looks
82: # a little better...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Yet Another Config File Parser Module
by Fastolfe (Vicar) on Dec 05, 2000 at 10:13 UTC | |
|
Re: Yet Another Config File Parser Module
by btrott (Parson) on Dec 05, 2000 at 07:16 UTC | |
by jynx (Priest) on Dec 05, 2000 at 07:27 UTC | |
|
Re: Yet Another Config File Parser Module
by deprecated (Priest) on Dec 20, 2000 at 21:34 UTC | |
by jynx (Priest) on Dec 21, 2000 at 00:42 UTC |