perloopbless

Perl read_config sub, oop or not?


I have a package (really just one subroutine) I use frequently to parse config file etc. Basically it looks like this:

sub get_settings {
        my %config;
        my $config = 'path...';

        unless(-r $config) {
                die("Couldn't read config");
        }
        open CONFIG, '<', $config or die $!;
        while(<CONFIG>) {
                next if (($_ eq "\n") or /^\;/);
                chomp;
                my($setting, $value) = split(/=/, $_);
                $config{$setting} = $value;
        }
        return %config;
}

Pretty basic, but I was wondering how (and if) this could/should be re-written to OOP? Really just for learning, never quite seen when and why to use bless. =)

Thanks!


Solution

  • The answer to the question has more to do with the programs you are using the package in than with the package itself.

    If this a pretty large OOP based apps/scripts then it definitely makes sense to OOP it because that is what the customer expects (the apps and the people writing these apps/scripts). Also having imperative style libraries stick out like a sore thumb and create complexity.

    Conversely if the package is used in shorter imperative scripts, then an OOP interface will conflict with the customer's expectation (i.e. the scripts + people developing them).

    Maybe you are migrating between approaches (e.g. the script become big and unwieldy and need to be better organised, maybe with OOP) in that case a settings/config kind of Class is a good place to start as they tend to be well separated and have clear lines of responsability.

    In short : do what makes most sense where the package is used.