Search code examples
perloopobjectmodulesubroutine

Creating two different objects through one Perl module


I'm writing Perl modules that allow users to create file and directory objects to manipulate the file system.

Example:

use File;
use Dir;

my $file = File->new("path");
my $dir  = Dir ->new("path");

This works out nicely, but what I would really like to be able to create both file and directory objects without having to use two separate modules.


To do this I came up with the following solution...

IO.pm:

use File;
use Dir;

use Exporter qw(import);
our @EXPORT_OK = qw(file dir);

sub file {
    my $path = shift;
    return File->new($path);
}

sub dir {
    my $path = shift;
    return Dir->new($path);
}

1;

test.pl:

use IO qw(file dir);

my $file = file("path");
my $dir  = dir ("path");

Now here's the problem, by doing this I eliminate the explicit call to new when the user creates a file or directory object. I'm sort of using the file and dir subroutines as constructors.

To me this code looks very clean, and is extremely simple to use, but I haven't seen many other people writing Perl code like this so I figured I should at least pose the question:

Is it okay to simply return an object from a subroutine like this, or does this scream bad practice?


Solution

  • That's perfectly fine.

    For example, Path::Class's file and dir functions return Path::Class::File and Path::Class::Dir objects respectively.

    If that was the only constructor the class provided, it would prevent (clean) subclassing, but that's not the case here.


    There is, however, the question of whether replacing

    open(my $fh, "path");
    opendir(my $dh, "path);
    

    with

    my $fh = file("path");
    my $dh = dir("path);
    

    is advantageous or not (assuming the functions return IO::File and IO::Dir objects).