Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl OOP Blessing

Tags:

perl

I'm new to Perl and I've been making my way through this tutorial http://qntm.org/files/perl/perl.html

Anyways, I'm working on creating a package that will take in a matrix and will perform various basic operations (i.e. gaussian elimination, rref, back sub, deterimants, etc). I have my constructor taking in a list of references, but I'm having some trouble blessing them so I can access them later. My code thus far:

main.pl:

use strict;
use warnings;
use Matrix;

my @list = ([1,1,1],[2,2,2]);
my $matrix = Matrix->new(@list);

$matrix->test();

Matrix.pm:

package Matrix;
    sub new(){
        my $class = shift;
        my $self = [];

        my @params = @_;
        $self = \@params;

        print scalar @{$self->[1]}; #just testing some output...(outputs 3 as expected)

        bless $self,$class;

        return $self;
    }

    sub test(){
        print @{$self->[1]}; #does not output anything
    }

1;

I'm assuming the problem is that the references that $self is referring to is not being blessed, but I'm not sure how to do this. Any help would be appreciated.

Thanks

like image 991
William Avatar asked Mar 22 '23 19:03

William


1 Answers

You forgot to actually define $self in test; it's not available for you automatically. This is why you should always put use warnings; use strict; in every Perl source file: so that the compiler will tell you about errors like these. (Also, there's no point in writing sub new() instead of sub new, and likewise for test; the function prototype is not only wrong but will be flat-out ignored when new is used as a method, i.e., how new is supposed to be used.)

like image 133
jwodder Avatar answered Mar 27 '23 22:03

jwodder