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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.