Perl Weekly Challenge 033: Count Letters & Formatted Multiplication Table
Count Letters
Create a script that accepts one or more files specified on the command-line and count the number of times letters appeared in the files.
From the example we can see that we should count the letters in a case insensitive way (see the lc
in the example below). Similarly to Challenge 032, we can use a hash to keep the counts.
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
my %count;
while (<>) {
++$count{ lc $1 } while /([a-zA-Z])/g;
}
for my $char (sort keys %count) {
say "$char: $count{$char}";
}
To iterate over the string, I used a regex match. It filters non-letters at the same time so there’s no need to use grep
.
Formatted Multiplication Table
Write a script to print 11×11 multiplication table, only the top half triangle.
Just eleven? This should be a challenge! Let’s write a general program that can output the table for any number (if your terminal window is wide enough).
To spice it up, we’ll use non-ASCII box drawing characters to print the table. You might need to configure your terminal properly if you don’t use UTF-8 regularly.
When formatting such a table, what we need to know in advance is the width a column which corresponds to the number of digits of the largest number. We’ll use printf to format the numbers.
use utf8;
tells Perl our script contains non-ASCII characters encoded in UTF-8, the open line, on the other hand, tells it to encode the output into UTF-8.
#!/usr/bin/perl
use warnings;
use strict;
use utf8;
use open OUT => ':encoding(UTF-8)', ':std';
my $MAX = shift;
my $width = 1 + length($MAX ** 2);
sub line {
my ($header, $from) = @_;
printf "%${width}s │", $header;
printf "%${width}s", "" for 1 .. $from - 1;
printf "%${width}d", $from * $_ for $from .. $MAX;
print "\n";
}
line('×', 1);
print '─' x (1 + $width), '┼', '─' x ($width * $MAX), "\n";
for my $x (1 .. $MAX) {
line($x, $x);
}
Note that we use the same subroutine to print the header line and all the multiplication lines.
Leave a comment