perlpass-by-referencetiebless

Perl: referencing/blessing question


The idea is to implement a class that gets a list of [arrays, Thread::Conveyor queues and other stuff] in a TIEHASH constructor,

use AbstractHash; 
tie(%DATA, 'AbstractHash', \@a1, \@a2, \$tcq);

What is a correct way to pass object references (like mentioned Thread::Conveyor objects) thus array references into constructor, so it can access the objects? Any cases when a passed object should be blessed?


Solution

  • As far as I can tell, objects are not objects unless they're bless-ed.

    That said, the constructor argument would simply be an arrayref of Thread::Conveyor objects:

    my $data = AbstractHash->tie ( \@a1, \@a2, \$tcq );
    

    where the constructor is defined in the AbstractHash package:

    sub tie {
    
        my $class = shift;  # Implicit variable, don't forget
    
        my $data = {
                     someArray => +shift,
                     queues    => +shift,
                     someValue => +shift,
                   };
    
        # $data starts life as a hashref, make it an 'AbstractHash'
    
        bless $data, $class; # $data is no longer a hashref
        return $data;        # AbstractHash object returned
    }