Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Why won't a hash in a hash work as a hash reference to create an object?

by Lady_Aleena (Chaplain)
on Apr 07, 2012 at 20:32 UTC ( #963939=perlquestion: print w/ replies, xml ) Need Help??
Lady_Aleena has asked for the wisdom of the Perl Monks concerning the following question:

I've have been going around in circles trying to get a grasp on objects, and when I finally go to give it a try, I can not get an object to work as I was hoping.

package Twitter::Objects; use strict; use warnings; use lib '..'; use Base::Data qw(data_file get_hash); my %accounts = get_hash( file => data_file('Twitter','account_totals.txt'), headings => [qw(screen_name followers friends updates)], ); sub new { my $self = \%accounts; bless($self); return $self; } 1;

Now, when I go to get data out of that object, I have to type my $foo = Twitter::Objects->new; print $foo->{Lady_Aleena}{updates};. I thought a way to shorten that would be the following.

package Twitter::Objects; use strict; use warnings; use lib '..'; use Base::Data qw(data_file get_hash); my %accounts = get_hash( file => data_file('Twitter','account_totals.txt'), headings => [qw(screen_name followers friends updates)], ); sub new { my ($account) = @_; my $self = \%{$accounts{$account}}; bless($self); return $self; } 1;

However, when using the above like so ... my $foo = Twitter::Objects->new('Lady_Aleena'; print $foo->{updates};, I get back an empty string. So, why does the subhash not work but the main hash does?

get_hash

Just in case you want to know.

sub get_hash { my %opt = @_; open(my $fh, '<', $opt{file}) or die("can't open $opt{file} $!"); my $line_number = 0; my %hash; while (my $line = <$fh>) { ++$line_number; chomp $line; my @values = split(/\|/,$line); my $n = 0; $hash{$values[0]}{sort_number} = $line_number if $opt{sort}; for my $heading (@{$opt{headings}}) { $hash{$values[0]}{$heading} = defined($values[$n]) ? $values[$n] + : ''; ++$n; } } return %hash; }
Have a cookie and a very nice day!
Lady Aleena

Comment on Why won't a hash in a hash work as a hash reference to create an object?
Select or Download Code
Re: Why won't a hash in a hash work as a hash reference to create an object?
by moritz (Cardinal) on Apr 07, 2012 at 21:12 UTC

      Thank you moritz. Quick question, what is the value of $class supposed to be?

      Have a cookie and a very nice day!
      Lady Aleena

        It's the name of the class. If you call new as a method:

        my $obj = Class->new;

        ... then it'll be the invocant.

        (Don't not call new as a method. You set yourself up for all kinds of mess that way.)


        Improve your skills with Modern Perl: the free book.

Re: Why won't a hash in a hash work as a hash reference to create an object?
by GrandFather (Cardinal) on Apr 08, 2012 at 21:52 UTC

    If all you do is use an object as a hash reference then there is not much point making it an object. However, looking at your code it seems there is scope for a useful object. It looks like get_hash is probably general purpose code so it may make sense to base a class around that: a class that wraps up a bunch of options that can be saved to and loaded from disk. Consider:

    use strict; use warnings; package OptionsBase; sub new { my ($class, %options) = @_; my $self = bless \%options, $class; $self->{headingsLU} = {map {$_ => 1} @{$options{headings}}}; return $self; } sub load { my ($self) = @_; open my $fIn, '<', $self->{file} or die ("Can't open $self->{file} +: $!"); while (defined (my $line = <$fIn>)) { chomp $line; my ($rowName, @values) = split (/\|/, $line); $self->{options}{$rowName}{sort_number} = $. if $self->{sort}; for my $heading (@{$self->{headings}}) { $self->{rows}{$rowName}{$heading} = shift @values || ''; } } } sub save { my ($self) = @_; open my $fOut, '>', $self->{file} or die ("Can't create $self->{fi +le}: $!"); for my $key (keys %{$self->{rows}}) { my @values = map {defined $_ ? $_ : ''} @{$self->{rows}{$key}}{@{$self->{headings}}}; print $fOut join ('|', $key, @values), "\n"; } } sub setOptions { my ($self, $key, %options) = @_; my @badOptions = grep {!exists $self->{headingsLU}{$_}} keys %opti +ons; die "Bad options: @badOptions\n" if @badOptions; @{$self->{rows}{$key}}{keys %options} = values %options; } sub getOptions { my ($self, $key, @options) = @_; my @badOptions = grep {!exists $self->{headingsLU}{$_}} @options; die "Bad options: @badOptions\n" if @badOptions; die "No such row: $key\n" if !exists $self->{rows}{$key}; return map {$_ => $self->{rows}{$key}{$_}} @options; } package TwitterOptions; push @TwitterOptions::ISA, 'OptionsBase'; sub new { my ($class, %options) = @_; return $class->SUPER::new( name => 'Twitter', file => 'account_totals.txt', headings => [qw(screen_name followers friends updates)], %options ); } package main; my $obj = TwitterOptions->new(); $obj->setOptions('joe', screen_name => 'Joe', followers => 'Freida'); $obj->save(); my $another = TwitterOptions->new(); $another->load(); my %options = $another->getOptions('joe', 'screen_name', 'followers'); print "$options{screen_name}'s followers are: $options{followers}\n";

    Prints:

    Joe's followers are: Freida

    This sample uses object inheritance to provide some common methods that act on option objects using the base class OptionsBase. TwitterOptions inherits those methods (that's what the ISA stuff is about) so all the methods provided in OptionsBase can be used with TwitterOptions objects. The neat thing now is that you can make new options classes that all behave in the same way, but have different sets of headers and file names etc.

    True laziness is hard work

      GrandFather, I am going to try to explain what I see, but I will probably have some of it wrong, so please correct me where I'm in error.

      1. It looks like new under package OptionsBase; is just setting the hash keys for the hash that is being created. I'm not exactly sure what headingsLU is doing.
      2. It looks like load under package OptionsBase; is getting the file and loading it into the hash.
      3. It looks like save under package OptionsBase; is saving the hash back to the file. (I normally just save without a subroutine, just open and print.)
      4. I can't tell what setOptions and getOptions are doing. I see an array called @badOptions, but I don't know where the bad options are coming from.
      5. I take it that I can split this up into two different modules at package TwitterOptions; since my original get_hash is its own beast separate from the Twitter code or would that completely mess up your ISA stuff?</c>
      6. I'm not exactly sure why you wrote something for modifying the hash, since that will only happen when another script is run which will modify the data file. (Also, followers is a number not a list. There is %followers that has the headings [qw(id screen_name greet)])

      The get_hash subroutine is one that I use everywhere in my work to create a hash from my data files. (movies, role playing, miscellany, etc)

      I think I'll just give you the bigger picture so you can see what I did and where I did it.

      Base::Data is where get_hash and even data_file are.

      Since I use get_root a lot in Base::Data, I'll include Base::Roots. That was where I was first trying out objects and couldn't figure it out there.

      So, if the top half of what you did could be put in a module on its own, maybe called Base::FileData or something, I would be happy to see how to split this up. You did a lot of work here and added complexities I have yet to understand, but I'll be looking over this over the next few days trying to figure it out.

      Have a cookie and a very nice day!
      Lady Aleena
        1. new is a constructor. It creates an object which may include doing a little house keeping to get the object into good initial shape. In this case it is generating a lookup table of the allowed column headings for internal use by other members of the class (setOptions and getOptions for example).
        2. load as you surmise is loading the hash. It is also providing empty strings for any missing columns and is providing a sort number based on the file line.
        3. "simply open and print" don't work for a hash. save ensures that only heading colums are output to the file and that they are output in the correct order correctly formatted. Actually both save and load could be beefed up to work with quoted strings and embedded newlines etc, but if you want that you'd have them use Text::CSV to do the heavy lifting. And guess what? All classes derived from OptionsBase then get the new magic at no added cost!
        4. Look at the line where @badOptions is set and figure it out now that you have had a sleep. setOptions and getOptions provide checked access to options. In particular they check that the options that you are getting or setting are ones that are allowed for the options class. That allows you to catch bad option stuff early make it easier to catch programming errors.
        5. ISA doesn't care where the base class comes from so long as it has been seen by the time methods are called on an object that needs to access the base class definition so it doesn't matter where OptionsBase lives. It would be usual for TwitterOptions to live in its own TwitterOptions.pm module and for that module to use OptionsBase in the OptionsBase.pm module.
        6. I'm not greatly interested in addressing your specific implementation details in the example I gave. Those are for you to sort out. However it makes sense to have a single cohesive class to handle reading and writing a set of options to persistent storage so I provided a load and save.

        The point of the example is exactly that you have a piece of common code (get_hash) that is used all over the place but presents a very raw and unsafe "interface". By wrapping that up in an object you can easily tailor it to different contexts (different lists if headings for example) and gain a cleaner way of managing your options with better sanity checking of usage. It also makes it easy in the future to change how you persist the options. If for example you were to realise that databases were wonderful (unlikely I know ;) ) and wanted to switch all your option files over to database tables you can facilitate that in one place by simply changing OptionsBase.

        True laziness is hard work
Re: Why won't a hash in a hash work as a hash reference to create an object?
by sundialsvc4 (Monsignor) on Apr 09, 2012 at 15:12 UTC

    May I say, in all respect and courtesy and politeness, m'Lady, perhaps it is that you are “thinking too deeply into it.”   Many object-oriented language implementations impose many strictures upon how the language must work; upon how things must be done.   Perl does not.   (And there are sound engineering reasons for it, which perhaps do not immediately meet the eye.)   Therefore, if you are, perhaps unconsciously, trying to carry-over the concepts taken from those languages into this one, you’re going to wind up mightily confused for a while.

    package is a declaration.   It simply notifies Perl about a name that is to be associated with all of the code that follows it, superseding any previous package-name or Perl’s default.   The significant thing here is that, when you refer to “a Perl object,” that object is always a package.   The subroutines in that package are the object’s methods; new is different as previously noted.   But the concept of packages, and the concept of objects, are only loosely related!

    Start with perldoc perltoot and read that well-written documentation page very slowly and carefully.   Especially when it talks about new, which it does several times.   Consider, again very slowly and carefully, just what the bless function is actually doing, and why.   Of what we mean when we say that something is “a blessed reference,” and, if you like, exactly how the Perl language system represents that notion.   (It is literally a bit.)

    Many object-oriented languages, as I said, are “object-oriented right down to the freckles on their skin.”   They simply can’t be approached in any other way.   And yet, here is Perl, and it implements the same concepts using just a small handful of concepts, artfully arranged, and never once does it say to you, “this is the Right Way ... you must do it This Way.”   Perl-heads are constantly saying, TMTOWTDI = There’s More Than One Way To Do It, and it takes a long time to grok the sheer genius(!) of what they are talking about.   You find yourself (or at least, I certainly did...) grasping around, saying, “where’s the rest of it?!”   But, then, you start to realize why this community uses the term, Monks.

      sundialsvc4, first thank you for the respect, courtesy, and politeness. You did not have to be any of those things, so I appreciate it. Perl is my first and only programming language, and I am learning programming concepts as I go. I had perltoot up in my browser as I was trying to write that object above, however the example in "Constructors and Instance Methods" did not show how a predefined data source, in my case an HoH, could be connected to an object. Even after reading perltoot, I made my best guess on how to reference a hash in a hash in an object even though my guess was wrong. Had perltoot started with package People; instead of package Person;, I may have gotten the hang of objects sooner.

      perltoot starts with a table for one person we know nothing about (in this case Jason), instead of starting with a table for several people for whom we have already gathered data (not only Jason, but his peers Norbert, Rhys, and Phineas too). Had perltoot started with the following and created package people; first, it would have been more enlightening to me.

      my $records = [ { name => "Jason", age => 23, peers => [ "Norbert", "Rhys", "Phineas"], }, { name => "Norbert", age => 24, peers => [ "Jason", "Phineas", "Michael"], }, { name => "Rhys", age => 22, peers => [ "Norbert", "Jason", "Robert"], }, { name => "Phineas", age => 23, peers => [ "Norbert", "Jason", "Alexandra"], }, ];

      I could possibly take an example object which had an A(ref)oH and converted it to an HoH in my objects. I was having a hard time with perltoot starting in what I consider the end.

      Have a cookie and a very nice day!
      Lady Aleena

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://963939]
Approved by GrandFather
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (9)
As of 2014-09-18 15:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (116 votes), past polls