Last time, a time long, long ago, in a universe far, far away, I left you with the following Perl 6 code (or something like it). This code reads in a series of book heights and displays the number of books of each height (in order from shortest to tallest).
my %num_of_height; for lines() { if m/^ \s* (\d+[\.\d+]?) [\s* x \s* (\d+)]? \s* $/ { my $height = +$0; my $num = +($1 || 1); %num_of_height{$height} += $num; } elsif ! m/^\s*$/ { note "Invalid line ignored: $_"; } } #| unique book heights seen, in order from shortest to tallest my @heights = sort { $^a <=> $^b }, keys %num_of_height; say "Histogram data:"; for @heights -> $height { my $num = %num_of_height{$height}; say "$height x $num"; }
As you may recall, this little bit of somewhat less-than-useful P6 script was inspired by a homework assignment in my daughter’s high-school statistics course. While she manually counted up the heights of the books we measured, in order to draw a histogram of the data, I wrote a Perl script to do the same counting.
Since then, for kicks, I’ve also hacked together about 50 lines of code to display an actual histogram of these data, with horizontal bars of *****
. I’m not going to go into that code here, because I did not write it at the time, but if you want, you can check it out on Github.
However, I did discover how succinctly Perl 6 could answer the other questions from the assignment. Continue reading