Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

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

by GrandFather (Saint)
on Apr 08, 2012 at 21:52 UTC ( [id://964036]=note: print w/replies, xml ) Need Help??


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

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

Replies are listed 'Best First'.
Re^2: Why won't a hash in a hash work as a hash reference to create an object?
by Lady_Aleena (Priest) on Apr 09, 2012 at 02:33 UTC

    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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://964036]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2024-03-28 09:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found