OK. Once again... Im pulling my hair out trying to figure something out. Im starting to play with making my own packages/modules. One of the benefits I am seeing is the ability to encapsulate your data within the module and only access the data through the modules routines. This is great.
In the process of playing around with this, I have come across the problem of how to return a hash that contains reference to arrays. Im still learning about using references so Im sure I just have something mixed up. Here is some example code similar to what Im doing with most of the unimportant stuff removed.
The module
package TestPackage; sub new () { my $class = shift; my %opts = @_; my $self = {}; if (exists($opts{'username'}) && (exists($opts{'password'}))){ $self->{'username'} = $opts{'username'}; $self->{'password'} = $opts{'password'}; bless $self, $class; }else{ return undef; } $self->_init_Authentication; return $self; } sub Identities () { my $self = shift; if (exists($self->{'identities'})) { return @{$self->{'identities'}}; }else { return undef; } } sub BuddyList () { my $self = shift; if (exists($self->{'buddy_list'})){ return %{$self->{'buddy_list'}}; }else{ return undef; } } sub _init_Authentication () { my $self = shift; ## ---- snip lots of code ---- ## assume $buddylist = "group1:name1,name2\ngroup2:name2,name3\n.. +.etc..." my %buddylist; my @groups = split /\n/, $buddylist; foreach (@groups) { my ($group,$names) = /^(.+?):(.+)/; $buddylist{$group} = [ split /,/, $names ]; } # ---- snip more code ---- # assume $myident = myname1,myname2, etc... my @identities = split /,/, $myident; $self->{'buddy_list'} = \%buddylist; $self->{'identities'} = \@identities; } 1;
The test script
#!/usr/bin/perl -w; use strict; use TestPackage; my $p = TestPackage->new ( username => 'zzspectrez', password => 'perlkicksbutt' ) || die "Couldn't create object.\n"; print "Identities: ", join (' ', $p->Identities), "\n"; #my %buddys = $p->BuddyList; my $buddys = $p->{'buddy_list'}; foreach my $key (keys %$buddys){ print "GROUP: $key\n"; print "NAMES: ", join (' ', @{$$buddys{$key}}), "\n"; }
The following works. But I cant seem to create a method to return the the hash properly. The $p->BudyList routine doesnt work. Instead I have to access the data directly, which I would rather not do. What am I doing wrong?!?!? I even tried having it return a hard coded hash.
Thanks!
zzSPECTREzz
In reply to Packages, references, & data hiding... by zzspectrez
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |