Re: [SPOILER] Perl 'Easy' Quiz of the Week #2005-1

Zed Lopez <[email protected]> Wed, 26 Jan 2005 15:38:07 -0800
Newsgroups gmane.comp.lang.perl.qotw.discuss
Message-ID <[email protected]>
Here's mine, substantially similar to Brad Greenlee's.

#!/usr/bin/perl
use warnings;
use strict;

my ($input, $output) = @ARGV;
my ($inputfh, $outputfh);

open $inputfh, "<$input" or die "Can't open $input: $!";
open $outputfh, ">$output" or die "Can't open $output: $!";

my %suffix;
my $currentpref = '';
while (<$inputfh>) {
  chomp;
  my ($pref, $suf) = (/^(\w+)\.([A-Z])$/);
  if ($currentpref and $pref ne $currentpref) {
    output_pref($currentpref);
    $currentpref = $pref;
  }
  $currentpref ||= $pref;
  $suffix{$suf}++;
}
output_pref($currentpref) if $currentpref;

sub output_pref {
  my $currentpref = shift;
  $suffix{M}++;
  print $outputfh "$currentpref.$_\n" for sort keys %suffix;
  %suffix = ();
}