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

Fellow Monks!

I am trying to construct the most general access method possible for objects. The way I see it, the maximum uses of one method accessing array data is three:

1) Pushing the input into the data.
2) If an array return walue is whanted, and no argument is given, return a copy (or ref to) the array.
3) Under the same conditions as 2) but a scalar is asked for, return the number of elements in the array (or the last index of it).
However, this presents a problem for me, since the following code does not give me what I want under 3):
package Labels::Level; use Carp::Datum (":all", $ENV{DATUM}); sub new{ DFEATURE my $f_,"Creating new Level"; my $invocer =shift; my $class = ref($invocer) || $invocer; my $self = {xmin => 0, xmax => 0, name => "", labels => [], @_}; bless($self,$class); return DVAL $self; } sub labels{ DFEATURE $f_; my $self = shift; if(@_){ my $inRef = shift; push @{$self->{'labels'}},$inRef; } else{ return DARY @{$self->{'labels'}} if wantarray; } my $out = @@{$self->{'labels'}}?$#{$self->{'labels'}}:0; return DVAL $out; } package main; use Labels::Level; $main::lvl=Labels::Level->new(xmax=>10,xmin=>0,name=>'myname'); $main::lvl->labels("labelref"); $main::lvl->labels("labelref2"); @main::out = $main::lvl->labels; print "@main::out"."::::".$main::lvl->labels."\n";
This always gives me:
labelref labelref2::::0
Can anyone tell me why, and what to do about it..
I am of course happy for all the help I can get!
/Dargosch

Replies are listed 'Best First'.
Re: Array troubles.. (Making a three-way method..)
by Baboon (Acolyte) on Jun 24, 2002 at 15:12 UTC
    While your code needs some improvements, I see an error here, which will be revealed using "use strict;" and "use warnings;" (or better yet just run your code using '-w' switch).

    I mean your lines

    my $out = @@{$self->{'labels'}}?$#{$self->{'labels'}}:0; return DVAL $out;
    Write them as just:
    return scalar @{$self->{'labels'}};
    Your more calculations are:
    1. wrong, because $#blabla returns -1 if no members in @blabla and your code needs at least adding '1' to it
    2. wrong, because your @@{blabla} will do nothing usefull at all (as I see it)

    Anyway, you seem to be lost and you need to rethink your idea and implementation, may be re-ask your question from other point.

    Personally, I advice you:
    1. Do not "use Carp::Datum" right now, because you should start with more obvious debugging techniques, such as using "use Data::Dumper" and just printing your debug values to STDERR, or may be "ptkdb" graphical debugger will greatly help.
    2. do not use such many temporary variables, when you can easily use function return value directly (as with "$inRef" variable)

    Best wishes,
    I.R.Baboon.