From d7fbc552897db1b0892557de50e2f9067db433bb Mon Sep 17 00:00:00 2001 From: Moritz Lenz Date: Thu, 29 Oct 2009 20:51:25 +0100 Subject: [PATCH] example for chapter 1 Also run pdflatex twice, we'll need that as soon as we have some back-and-forth reference, and it's already warning --- Makefile | 5 +++-- src/basics.pod | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 src/basics.pod diff --git a/Makefile b/Makefile index 9cf656f..1c60e63 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,5 @@ -CHAPTERS = src/preface.pod \ +CHAPTERS =src/basics.pod \ + src/preface.pod \ src/multi-dispatch.pod \ src/classes-and-objects.pod \ src/regexes.pod \ @@ -15,7 +16,7 @@ build/mmd-table.pdf: src/mmd-table.svg $(INKSCAPE) --export-pdf=build/mmd-table.pdf -D src/mmd-table.svg build/book.pdf: build/book.tex build/mmd-table.pdf - cd build && pdflatex book.tex + cd build && pdflatex book.tex && pdflatex book.tex build/book.tex: $(CHAPTERS) perl bin/book-to-latex $(CHAPTERS) > build/book.tex diff --git a/src/basics.pod b/src/basics.pod new file mode 100644 index 0000000..cdc44fd --- /dev/null +++ b/src/basics.pod @@ -0,0 +1,58 @@ +=head0 The Basics + +Perl has traditionally been very strong in the area of gathering information +from text files, and report it. In fact that is what Perl was written for +originally. + +A typical such problem might look like this: You host a table tennis +tournament, and the referees tell you the results of each game in the format +C, which means that C won against +C by 3 to 2 sets. You need a script that sums up how many games and +sets each player has won, and thus determines the overall winner. + +The input data looks like this: + + Beth Ana Charlie Dave + Ana vs Dave | 3:0 + Charlie vs Beth | 3:1 + Ana vs Beth | 2:3 + Dave vs Charlie | 3:0 + Ana vs Charlie | 3:1 + Beth vs Dave | 0:3 + +Where the first line is just the list of players, and every line after that is +a result of a match. + +Here's one way to solve that problem in PerlĀ 6: + + use v6; + + my $file = open 'scores'; + + my @names = $file.get.split(' '); + my %games; + my %sets; + %games{@names} = 0 xx @names; + %sets{@names} = 0 xx @names; + + for $file.lines -> $line { + my ($pairing, $result) = $line.split(' | '); + my ($p1, $p2) = $pairing.split(' vs '); + my ($r1, $r2) = $result.split(':'); + %sets{$p1} += $r1; + %sets{$p2} += $r2; + if $r1 > $r2 { + %games{$p1}++; + } else { + %games{$p2}++; + } + } + + my @sorted = @names.sort({ %sets{$_} }).sort({ %games{$_} }).reverse; + for @sorted -> $n { + say "$n has won { %games{$n} } games and { %sets{$n} } sets"; + } + + + +=for vim: spell