Blob


1 #!/usr/bin/perl
3 # The Professor has to read a logfile that looks like the example we show
4 # here. You can get sample data files from the Downloads section of
5 # http://www.intermediateperl.com/:
7 # Gilligan: 1 coconut
8 # Skipper: 3 coconuts
9 # Gilligan: 1 banana
10 # Ginger: 2 papayas
11 # Professor: 3 coconuts
12 # MaryAnn: 2 papayas
13 # ...
14 #
15 # He wants to write a series of files, called gilligan.info, maryann.info,
16 # and so on. Each file should contain all the lines that begin with that
17 # name. (Names are always delimited by the trailing colon.) At the end,
18 # gilligan.info should start with:
19 #
20 # Gilligan: 1 coconut
21 # Gilligan: 1 banana
22 #
23 # Now, the logfile is large and the coconut-powered computer is not fast,
24 # so he wants to process the input file in one pass and write all output
25 # files in parallel. How does he do it?
26 #
27 # Hint: Use a hash keyed by castaway name and whose values are IO::File
28 # objects for each output file. Create those files if they don't exist yet,
29 # and overwrite them if they do.
31 use v5.24;
32 use warnings;
33 use strict;
34 use utf8;
35 use local::lib;
37 use IO::Tee;
39 my %files;
40 while (<>) {
41 chomp(my ($castaway, $item) = split /: /);
42 $castaway = lc($castaway);
43 if(!defined($files{$castaway})) {
44 $files{$castaway} = IO::File->new("$castaway.info", "w")
45 or die "Unable to write '$castaway.info': $!";
46 }
47 print {$files{$castaway}} "$castaway: $item\n";
48 }