J0HN_TIT0R
J0HN_TIT0R

Reputation: 323

Read only attributes being filled without writer method in Moose

I'm using Moose to create an object oriented class in Perl.

I have a number of attributes which I want to be read only which I've declared like this:

package BioIO::SeqIO;
use Moose;
use namespace::autoclean;
use MooseX::StrictConstructor;
use MooseX::Types::Moose qw(ArrayRef HashRef Int Str);
use FinalTypes::MyTypes qw(FileType);

has '_gi'      => (isa      => ArrayRef,
                   is       => 'ro',
                   init_arg => undef,
                   writer   => '_writer_gi');

I also have a BUILDER method which looks like this:

sub BUILD {
    # Confessing with usage string if incorrect number of arguments used.
    @_ == 2 or confess getErrorString4WrongNumberArguments();
    # Initializing local variable with subroutine input.
    my ($self) = @_;
    # Creating BioIO::SeqIO object for GenBank or FASTA file.
    $self->fileType =~ /genbank/i ? $self->_getGenbankSeqs() : $self->_getFastaSeqs();
}

My code works fine, however, I get a warning with the following test:

dies_ok {BioIO::SeqIO->new(filename => $fileNameIn, fileType => 'fasta', => _gi => [])}     '... dies when _gi sent to BioIO::SeqIO constructor';

Here is the warning:

Use of uninitialized value $gi in hash element at BioIO/SeqIO.pm line 256, <$fh> chunk 1.

Lastly, here is line 256 for that error:

$hashDef{$gi} = $def;

I think that I'm getting a warning because the program is not dying as soon as the user attempts to write to _gi, however, I don't know how to ensure this happens?

Upvotes: 0

Views: 61

Answers (1)

amon
amon

Reputation: 57640

In the attribute definition, note that the init_arg is set to undef, i.e. deleted:

has '_gi'      => (isa      => ArrayRef,
                   is       => 'ro',
                   init_arg => undef,
                   writer   => '_writer_gi');

The init arg is the name of the argument in the constructor call. As it is set to undef, you cannot initialize it via the constructor, but only via the writer method (here, an internal method called _writer_gi is created).

Upvotes: 1

Related Questions