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

Hi!
Simple task: I have a class called "settings", and it's purpose is to hold information for printing a page where our customers can change several settings.
. It's supposed to hold a hash with name/value pairs, and it will have a method so that I dynamically can add settings. Finally, I want to print the result with another method.

I know how to do most of it, but I don't know how to create a hash as a data member that holds name/value-pairs. Howe can I do that?

Replies are listed 'Best First'.
Re: Hash in class?
by almut (Canon) on May 25, 2010 at 13:22 UTC
    but I don't know how to create a hash as a data member
    $self->{myhash} = {};

    But maybe you don't even need an extra hash, as Perl objects often are hashes (like the $self here)...  so unless you have other object attributes that might get in the way, you could maybe store the key-value pairs in the object directly.

    (Update)  With extra hash:

    package MyClass; sub new { my $class = shift; my $self = { @_ }; $self->{myhash} = {}; return bless $self, $class; } sub set_attr { my $self = shift; my ($key, $val) = @_; $self->{myhash}{$key} = $val; } sub get_attr { my $self = shift; my $key = shift; return $self->{myhash}{$key}; } package main; my $obj = MyClass->new(); $obj->set_attr( foo => "bar" ); print $obj->get_attr("foo"), "\n";

    Without:

    package MyClass; sub new { my $class = shift; my $self = { @_ }; return bless $self, $class; } sub set_attr { my $self = shift; my ($key, $val) = @_; $self->{$key} = $val; } sub get_attr { my $self = shift; my $key = shift; return $self->{$key}; } ...
Re: Hash in class?
by NetWallah (Canon) on May 25, 2010 at 14:57 UTC
    Another way, with auto-generated accessors, and parameter name validation. Also allows setting parameters in the "new" call. Avoids namespace collision by using a separate namespace for USERSETTINGS.
    use strict; use warnings; {package MyClass; my @usersettings = qw|bgcolor fgcolor carmodel hairstyle sexualprefere +nce foo bar baz|; foreach my $s (@usersettings) { eval "sub setting_$s : lvalue { \$_[0]->{USERSETTINGS}{$s} }" +; $@ and die "Error setting member $s : $@" } sub new { my $class = shift; my %options = @_; # Remaining params are optional user settings #my $self = { USERSETTINGS=> {map # {exists $options{$_} ? ($_=>$options{$_}):()} # @usersettings }}; my $self = {}; for my $opt(keys %options){ grep {$opt eq $_} @usersettings or die "invalid option:$opt"; eval "setting_$opt(\$self) ='$options{$opt}'" ; $@ and die "Error setting option $opt : $@" } return bless $self,$class; } 1; } #--------------------------------------- package main; my $obj = MyClass->new( carmodel=>"BMW" ); $obj->setting_foo = "bar"; print "FOO=" . $obj->setting_foo . "; car=" . $obj->setting_carmodel ."; \n";

         Syntactic sugar causes cancer of the semicolon.        --Alan Perlis