Hi perlbeginner10, apart from davido's good post your question has had the misfortune to only receive replies from our Anonymous Troll (whose posts have been deleted by now), so I thought I'd add some more detail just so you know the content/noise ratio here is usually quite high.
The decision whether to create an object to store a given data structure ultimately boils down to one question IMO: Do you want your data structure to just contain data or should it contain data-specific behaviour as well? As davido rightly pointed out, you can create a data structure of arbitrary complexity using a hash (which in turn contains references to other data structures etc.). For example, the requirement you give in your post (a string and an array in a structure) can be fulfilled like this:
my %ruler = ( title => "King",
fiefdoms => ["Narnia","Gondor","Scotland"] );
(The [] brackets around the fiefdoms create an anonymous array, see perldoc perldsc for more on this.)
If this is all you want, fine, no need for an object. But if you also want the data structure to be able to exhibit some behaviour, for example
$ruler->list_fiefdoms();
You'd implement an object, e.g. (this is a bare-bone skeleton object only and you almost certainly want to do this differently):
package Ruler;
sub new {
bless $_[1],$_[0];
}
sub list_fiefdoms {
my $self = shift;
print join(",",@{$self->{fiefdoms}})."\n";
}
1;
Now you could create the object with
use Ruler;
my $ruler = Ruler->new({ title => "Tyrant",
fiefdoms => ["Mordor","Giedi Prime","Texas"]
+ });
$ruler->list_fiefdoms();
And it would print the list. Note this still implements the underlying data structure as an (anonymous) hash, the only difference is that you now also have behaviour coupled with the structure which can manipulate the contained data.
Hope that helps.
There are ten types of people: those that understand binary and those that don't.
|