%Pet_Food = (
'dog' => 'dog chow',
'cat' => 'cat chow',
'parakeet' => 'birdseed'
);
# $pet_type should be 'dog', 'cat', or 'parakeet'
my $food = $Pet_Food{$pet_type};
####
@Pet_Types = ("dog", "cat", "dog", "parakeet", "dog", "cat");
my %type_table = ();
foreach my $type ( @Pet_Types ) {
$type_table{$type}++;
}
my @unique_types = sort keys %type_table;
# @unique_types winds up with 'cat', 'dog', and 'parakeet'
##
##
%Valid_Pets = (
'dog' => 1,
'cat' => 1,
'parakeet' => 1,
'lemur' => 1
);
# $pet_type should contain 'dog', 'cat', 'lemur' etc...
# but might not.. we die if it doesn't
exists $Valid_Pets{$pet_type}
or die "I'm sorry, '$pet_type' is not a valid pet\n";
##
##
name=fluffy species=rabbit weight=5 price=10.00
name=fido species=dog weight=15 price=30.15
name=gul_ducat species=cat weight=10 price=40.20
##
##
while () {
my %pet = parse_pet($_);
print "Name: $pet{'name'}\n";
}
sub parse_pet {
my ($line) = @_;
my @param_pairs = split(/\s/, $line);
my %params = ();
foreach my $param ( @param_pairs ) {
my ($name, $value) = split(/=/, $param, 2);
$params{$name} = $value;
}
return %params;
}
##
##
while () {
my $pet = parse_pet($_);
print "Name: $pet->{'name'}\n";
}
sub parse_pet {
my ($line) = @_;
my @param_pairs = split(/\s/, $line);
my %params = ();
foreach my $param ( @param_pairs ) {
my ($name, $value) = split(/=/, $param, 2);
$params{$name} = $value;
}
return \%params;
}
##
##
# Note: Bad code! No krispy kreme!
if ( $pet_type eq 'dog' ) {
print_dog_page();
}
elsif ( $pet_type eq 'cat' ) {
print_cat_page();
}
elsif ( $pet_type eq 'lemur' ) {
print_lemur_page();
}
# .. ad nauseum
##
##
%Pet_Pages = (
dog => \&print_dog_page,
cat => \&print_cat_page,
lemur => \&print_lemur_page,
);
my $page_sub = $Pet_Pages{$pet_type}
or die "Invalid pet type\n";
&$page_sub();