jnoirel has asked for the wisdom of the Perl Monks concerning the following question:

Hi there,

I'm trying to develop a package DATASTORE used like this

$D = new DATASTORE 'dir', 'filename'; while($_ = $D->getline) { [...] }

The added benefit of using DATASTORE (in case you're wondering) is that it does some work towards automatically locating the data files I want based on some local config. I'd like the $D variable to inherit all the methods from IO::File.

package DATASTORE; use parent 'IO::File'; sub new { my ($class, @args) = @_; my $filename; [...] $self = $class->SUPER::new($filename, 'r'); return $self if defined $self; }

That seems to work for me. Now what I'm not sure about is how you'd adapt the code so that depending on the extension, it uses IO::File OR IO::Uncompress::Gunzip (if the extension is GZ).

Would this be something that's easy to do?

Joss

Replies are listed 'Best First'.
Re: Inherit methods from IO::File and IO::Uncompress depending on file extension
by Corion (Patriarch) on Apr 28, 2015 at 11:10 UTC

    Don't try to change DATASTORE, have two classes, DATASTORE::plain and DATASTORE::gzip.

    I would make DATASTORE->new return one of the two classes, depending on the filename.

Re: Inherit methods from IO::File and IO::Uncompress depending on file extension
by kcott (Archbishop) on Apr 28, 2015 at 19:12 UTC

    G'day jnoirel,

    Welcome to the Monastery.

    Note: this response is solely about your intended usage.

    I'm trying to develop a package DATASTORE used like this

    $D = new DATASTORE 'dir', 'filename';

    That's called Indirect Object Syntax and, if you follow that link, you'll see:

    "Outside of the file handle case, use of this syntax is discouraged as it can confuse the Perl interpreter. See below for more details."

    The section right above that, Invoking Class Methods, has additional useful information.

    Of lesser concern, but worth considering, is the class name DATASTORE. Tokens in all uppercase are typically either reserved words (e.g. SUPER, AUTOLOAD, etc.) or constants (e.g. use constant XXX => 1;). The choice is entirely up to you; my choice would probably be Datastore.

    Putting all that together, usage might look more like:

    my $datastore = Datastore::->new('dir', 'filename');

    -- Ken