outrunthewolf
outrunthewolf

Reputation: 135

How to use hashes correctly in perl class

I learned to create a new class like this, with a hash as part of the instantiation:

sub new {
    my $class = shift;
    my( $response, $config ) = @_;

    my $self = {
       _response => $response
       _config => $config
    };

    bless $self, $class;
    return $self;
}

sub getConfig {
  my( $self ) = @_;
  return $self->{_config};
}

sub getResponse {
  my( $self ) = @_;
  return $self->{_response};
}

When I create the class I send some configuration to it on instantiation.


my $response = {
  "my" => "response"
}

my $config = {
  "my" => "config"
}

$inst = MyClass::Class->new($response, $config);

When I get that information back it seems to work fine.

Data::Dumper

print Dumper $insta->getConfig();

$VAR = {
  "my" => "config"
}

Now it turns out that the config hash i'm being given looks like this:

%R_CONFIG = (
   "my", "config"
);

When I put that into my codebase all hell breaks loose:

$inst = Class->new($response, %config);

Im clearly making some fundamental mistakes. And I cant seem to get any solid information back from debugging, because everything is still saying its a hash when I use say ref() for example.

What mistake have I made with the creation of this class in regards to hashes?

Upvotes: 0

Views: 60

Answers (1)

ikegami
ikegami

Reputation: 385546

You can only pass scalars to subs.

$inst = Class->new($response, %config);

is the same as

$inst = Class->new($response, "my", "config");

Your method expects a reference to a hash, so you should be using

$inst = Class->new($response, \%config);

Upvotes: 3

Related Questions