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

Hello,

I've been searching and trying to find out how to return a perl module pointer that allows me to do the following:

# data is a pointer $data = ABC::readdatafile($filename); print "$data"; # output of print is: ABC::Data=SCALAR(0xc7918) # my goal is to be able to do use this and features like: $high = $data->get_high($signal); $low = $data->get_low($signal);
above is what I want to do.

When I read the data file (it's a large binary file, with many different data types, stored inside a module), I'm only returning a SCALAR element, with no module information.

#(inside the module) my $ref = \@data; return($ref);

ie. it's returning SCALAR(0xc7918) and not ABC::Data=SCALAR(0xc7918)

I have another module I am using (external module, source code not available) which uses this method, and I would like to follow it.

I would appreciate any suggestions!! Thank you!

Replies are listed 'Best First'.
Re: Returning module pointer
by dragonchild (Archbishop) on May 04, 2005 at 18:27 UTC
    bless

    • In general, if you think something isn't in Perl, try it out, because it usually is. :-)
    • "What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?"
      Thank you Dragonchild. That worked. I wasn't aware bless could be used for this. Live and learn! Thanks again.
Re: Returning module pointer
by gellyfish (Monsignor) on May 05, 2005 at 09:48 UTC

    Whilst it is perfectly valid to bless something into a package in a subroutine in another package, for future maintenance purposes you might want to abstract this further so that the ABC::Data object is actually being created in its own constructor:

    package ABC; sub readdatafile { my ( $filename) = @_; # get the data into array as required return ABC::Data->new(\@data); } package ABC::Data; sub new { my ( $class, $ref) = @_; return bless $ref, $class; }
    You probably would want to have more logic in ABC::Data::new() to check you really have got the right type of reference and so forth, but the advantage of doing this is that if at some point in the future you need to do some further processing on the data that is peculiar to the ABC::Data 'class' then you can stick it in the constructor without troubling the code that reads the file etc.

    /J\