<> wrote in comp.lang.perl.misc:
> wrote:
> >
> > For a given config file, Foo.conf with content along the lines,
> > Key1=Value1, I'd like to access the keys and values from my Perl
> > script, useOOP.pl, as, $obj->value("key1") ; which would give me
> > "value1".
> >
> > ------------------CfgLoader.pm-----------------------------
> .
> .
> .
> > sub loadCfg()
> > {
> > my ($self,$file) = @_ ;
> > print "Loading configuration: $file\n" ;
> >
> > open(IN,"$file") or die "Cant open $file: $!\n" ;
> > while(<IN>)
> > {
> > chomp ;
> > next if ( /^(#|$)/ ) ;
> > ($key,$value) = split(/\=/,$_) ;
> > print "Key: $key Value: $value\n" ;
> > $hash{$key} = $value ;
> > }
> > close(IN) or die "Cant close file: $!\n" ;
> > }
>
>
> Dear Prabh,
>
> I noticed that you used "use strict;" and "use warnings;" in the
> file "useOOP.pl". Good for you! However, it's also good to include
> them in CfgLoader.pm, as they will point out (at least) one error to
> you.
>
> Right off the bat, I see that you are populating %hash inside
> loadCfg() when it is never declared. Instead of:
>
> $hash{$key} = $value;
>
> I think you mean to say:
>
> $self->{$key} = $value;
>
> that way you can use $obj->{key1} to retrieve "value1".
I agree that the key/value pairs should probably go into the object and
not in some class-global hash (though that is a valid alternative too).
However, $obj->{key1} is no way to access an object. An object
encapsulates its implementation, but $obj->{key1} exposes the
implementation as a hash.
Instead there should be accessor methods for each key expected in the
config file to access the corresponding value (untested)
sub get_key1 { $_[ 0]->{ key1} }
etc.
For this approach you need to know beforehand which keys can possibly
appear in a config file. If you expect keys that aren't known until
run time, a general accessor can be used:
sub get_any_key {
my ( $conf, $key) = @_;
$conf->{ $key};
}
In that case, individual accessors can be derived from the general one
sub get_key1 { shift()->get_any_key( 'key1') }
Anno
--
If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.
--
If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.