#!/usr/bin/perl -w =head1 NAME who_likes.pl =head1 DESCRIPTION Compile a list of vegetables with the names of the people who like them. =head1 INPUT A list of people and (at most) three vegetables they like. Each line in the input consists of the person's name followed by a colon, a space, then a list of the vegetables they like. The vegetables are separated by comma + space. The string "--" is used instead of a list of vegetables when a person doesn't like B vegetables. Sample: Paul: onions, rutabagas, beets Xerxes: -- Yolanda: squash, peas, beets Zainab: beets, broccoli, Brussels sprouts =head1 OUTPUT Like the input, but the other way around: each line consists of the name of a vegetable followed by a colon, a single space, and a list of the vegetables they like. The vegetables are listed in alphabetical order. Sample: beets: Paul, Yolanda, Zainab broccoli: Zainab Brussels sprouts: Zainab onions: Paul peas: Yolanda rutabagas: Paul squash: Yolanda =cut use strict; use warnings; # Get command-line arguments # Usage: # perl who_likes.pl rutabagas input/vegetables.txt output/likes.txt my ($vegetable, $input_file, $output_file) = @ARGV; # Here's where we'll keep the information on who likes what my $what_they_like; my ($input_handle, $output_handle); # Open the input and output files open $input_handle, '<', $input_file or die "Can't open input file '$input_file': $!"; # Ask everyone what they like $what_they_like = collect_information($input_handle); # Answer questions about who likes what report_information(%$what_they_like); # Answer questions about who likes what answer_questions($what_they_like); sub collect_information { print STDERR "Collecting information...\n"; my %who_likes_what; while (defined(my $line = <$input_handle>)) { # For each line in the input file... # *** FILL THIS IN *** # Remember the information $who_likes_what{$name} = $vegetables; } return \%who_likes_what; } sub report_information { my (%name2veggies) = @_; my %veggie2names; my @names = keys %name2veggies; foreach my $name (@names) { # *** FILL THIS IN *** } my @veggies = keys %veggie2names; foreach my $veggie (@veggies) { # *** FILL THIS IN *** } } sub answer_questions { my ($likes) = @_; print "Answering questions...\n"; while (1) { print "Name? "; my $name = ; last unless defined $name; chomp $name; if (exists ) { my $vegetables = $likes->{$name}; if ($vegetables eq '') { print "$name doesn't like any vegetables!\n"; } else { print "$name likes $vegetables.\n"; } } else { print "Sorry, I don't what $name likes.\n"; } } }