Sumit
Sumit

Reputation: 2023

Getting issues in object oriented perl

I am new to OO perl. I am trying to write one simple program but getting the error.

Created a package Employee.pm as

package Employee;

sub new {
    my $class = shift;
    my $self = {};
    bless $self, $class;
    return $self;
}

sub get_names {
    my $self = @_;
    print " getting the names \n";
    return $self;
}

sub set_names {
    my ($self, $last_name) = @_;
    $self->{last_name} = $last_name;
    return $self->{$last_name};
}
1;

And created a .pl file as

use strict;
use warnings;

use Employee;

my $obj = new Employee("name" => "nitesh", "last_name" => "Goyal");

my $val = $obj->get_names();

print %$val;

my $setName = $obj->set_names("kumar");

print "$setName \n";

I am getting error as

"Can't use string ("1") as a HASH ref while "strict refs" in use at class1.txt line   10."

Upvotes: 2

Views: 77

Answers (1)

TLP
TLP

Reputation: 67908

The error

"Can't use string ("1") as a HASH ref ..

Comes from this part:

sub get_names {
    my $self = @_;

When an array is put in scalar context, it returns its size. Since you call the sub with

$obj->get_names();

Only one argument is passed, which is the object, so @_ contains 1 argument, and its size is 1, therefore in the sub get_names, the variable $self is set to 1. Hence the error. What you probably should do is

my $self = shift;

But then, that will not do anything, because you never stored the names in your constructor. As mpapec said, you should do

my $self = { @_ }; 

in the constructor sub new.

Also, in get_names, you simply return the object, which is not very useful. You should perhaps return $self->{name} and $self->{last_name}.

Upvotes: 2

Related Questions