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

I have implemented a class called cell and trying to store a char to it. I find that there is a problem to retrieve the char with my setter and getter.

#This is the detail of the class: package Cell; sub new{ my $class = shift; my $self = { content => -1, }; return bless $self, $class; } #This is my setter and getter sub setContent{ my ($self,$ch) = @_; $self->{content} = $ch; print("stored char".$self->{content}."\n"); } sub getContent{ my $self = @_; print("passing back char".$self->{content}."\n"); return $self->{content}; } # this is the way i used the class my $ch = "a"; my $cell = Cell->new(); $cell->setContent($ch); my $testvar = $cell->getContent(); print("test start\n".$testvar); print("test end\n"); #

I find that I am able to pass the char to the setter and should be stored in $self->{content}, but when trying to retrieve char using getter, $self->{content} become empty

Replies are listed 'Best First'.
Re: How to correct pass variable to and from called function?
by haukex (Archbishop) on Apr 02, 2019 at 07:36 UTC

    If you Use strict and warnings, which you always should, then you would see the error message "Can't use string ("1") as a HASH ref while "strict refs" in use".

    In my $self = @_;, you're using the array @_ in scalar context, which returns the number of elements, 1. You want either my ($self) = @_; or my $self = shift; instead. The former causes the right-hand side to be evaluated in list context, returning the elements of the array, and for the latter, see shift.