views:

62

answers:

4

I am trying to write a package in perl. I need one of the members to be a hash. However, when I reference and run the program, I cannot get it to work with the usual syntax. If I have:

sub new
{
my $class = shift;
my $self = {
    textfile => shift,
    placeholders => ()
};
bless $self, $class;
return $self;
}

Is there any way of making "placeholders" a hash I can access via $self->{placeholders} ?

Thanks

+6  A: 

Yes, but you have to make it a hash reference.

$self = {
   textfile => shift,
   placeholders => { }         #  { }, not ( )
};
...


$self->{placeholders}->{$key} = $value;
delete $self->{placeholders}->{$key};
@keys = keys %{$self->{placeholders}};
foreach my ($k,$v) each %{$self->{placeholders}} { ... }
...
mobrule
IT WORKS! Thank you so much! I suppose I should have figured that out. Thanks again!
Feynman
Feel free to accept mobrule's answer if it solved your problem. :)
brian d foy
Too many right answers here. Shows what we are all doing at the end of the day... :)
Eric Strom
+4  A: 

() constructs an empty list. This is fine when you are assigning to a %hash but otherwise, Perl just treats it as an empty list which is merged into the surrounding list. Just as you did when you assigned to $self, you need to use the curly braces { } to construct an anonymous hash reference.

Eric Strom
+6  A: 

All members of aggregates (arrays, hashes, and objects that are arrays are hashes) are scalars. That means that an item in a hash is never another array or hash, but it can be an array or hash reference.

You want to do (to a first approximation):

sub new {
  my $class = shift;
  my ($textfile) = @_;
  my $self = {
    textfile => $textfile,
    placeholder => {},
  };
  return bless $self, $class;
}

And then when you use it (assuming that you also have a placeholder accessor), you can use $obj->placeholder->{key}, %{ $obj->placeholder }, etc.

hobbs
+4  A: 

You want a hash reference. Use curly braces instead of parentheses:

sub new { 
     my $class = shift; 
     bless { textfile => shift, placeholders => {} }, $class; 
     }
brian d foy