%movies = (
'Gone with the Wind' => {
year => 1939,
stars => ['Clark Gable', 'Vivien Leigh'],
director => 'George Cukor'
},
'Wizard of Oz, The' => {
year => 1939,
stars => ['Judy Garland', 'Billie Burke'],
director => 'Victor Fleming'
}
# etc.
);
####
for $key (sort keys %movies) {
print "$key:\n";
print " Year: $movies{$key}->{year}\n";
print " Stars: ", join(', ', @{ $movies{$key}->{stars} }), "\n";
print " Director: $movies{$key}->{director}\n\n";
}
------------------Prints--------------
Gone with the Wind:
Year: 1939
Stars: Clark Gable, Vivien Leigh
Director: George Cukor
Wizard of Oz, The:
Year: 1939
Stars: Judy Garland, Billie Burke
Director: Victor Fleming
##
##
package MyDVDs;
# Creates a reference as a hash ref, "blesses it" into the
# current package, and returns the reference.
sub new {
my $self = {};
bless $self;
return $self;
}
# Simple get/set accessor. If you pass it something, it will add or
# replace (set) whatever is there. Always returns whatever it has (get).
sub title {
my $self = shift;
$self->{title} = shift if @_;
return $self->{title};
}
sub year {
my $self = shift;
$self->{year} = shift if @_;
return $self->{year};
}
# A variation, storing data in an array. A simple improvement might be
# to remove duplicates.
sub stars {
my $self = shift;
push @{$self->{stars}}, @_ if @_;
return join(', ', @{$self->{stars}});
}
sub director {
my $self = shift;
$self->{director} = shift if @_;
return $self->{director};
}
##
##
use MyDVDs;
# You'd probably load this directly from some source, creating anonymous
# objects and sticking them in an array, but I have to go to a meeting soon...
# Notice how easy it is simple it is to add data.
my $movie1 = MyDVDs->new;
$movie1->title('Gone with the Wind');
$movie1->year(1939);
$movie1->stars('Clark Gable', 'Vivien Leigh');
$movie1->director('George Cukor');
my $movie2 = MyDVDs->new;
$movie2->title('Wizard of Oz');
$movie2->year(1939);
$movie2->stars('Judy Garland', 'Billie Burke');
$movie2->director('Victor Fleming');
push @list, $movie1, $movie2;
# And how is this for simplicity of accessing the data?
for $movie (@list) {
print $movie->title, ":\n",
" ", $movie->year, "\n",
" ", $movie->stars, "\n",
" ", $movie->director, "\n\n";
}
------------------Prints--------------
Gone with the Wind:
Year: 1939
Stars: Clark Gable, Vivien Leigh
Director: George Cukor
Wizard of Oz, The:
Year: 1939
Stars: Judy Garland, Billie Burke
Director: Victor Fleming