I’ve been doing the Perl Weekly
Challenges This week’s was about
counting letters and generating a multiplication table.
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.
Even before I've finished reading I've broken this down mentally into
"turn each line into letters, then for each one add to the count for
that letter". Thus:
my %o;
while (<>) {
my $a=lc($_);
$a =~ s/[^a-z]//g;
map {$o{$_}++} split '',$a;
}
foreach my $k (sort keys %o) {
print "$k: $o{$k}\n";
}
This hits several of the syntax differences in Perl6.
my %o;
for lines() {
my $a=lc($_);
$a ~~ s:g /<-[a .. z]>//;
map {%o{$_}++}, split '',$a;
}
for sort keys %o -> $k {
print "$k: %o{$k}\n";
}
Write a script to print 11x11 multiplication table, only the top
half triangle.
On a terminal window, this is a job for printf.
my $n=11;
my $m1=length($n)+1;
my $m2=length($n*$n)+1;
my $fmt='%'.$m1.'s%1s'.(('%'.$m2.'s') x $n)."\n";
printf($fmt,'x','|',(1..$n));
printf($fmt,'-' x $m1,'+',('-' x $m2) x $n);
foreach my $row (1..$n) {
my @a=($row,'|');
foreach my $column (1..$n) {
if ($column < $row) {
push @a,'';
} else {
push @a,$row*$column;
}
}
printf($fmt,@a);
}
And Perl6 works similarly, except that length() is no longer used.
my $n=11;
my $m1=$n.chars+1;
my $m2=($n*$n).chars+1;
my $fmt='%' ~ $m1 ~ 's%1s' ~ (('%' ~ $m2 ~ 's') xx $n) ~ "\n";
(etc.)
But that was too easy. Why not do it in Postscript as well? The hard
bit is getting the numbers out into string form so that they can be
displayed – and, oddly, there's no right-align option. (I could have
used stringwidth, but I was lazy.)
/n 11 def
/scale 25 def
/fs 12 def
20 650 translate
/Helvetica findfont
fs scalefont setfont
1 1 n {
/x exch def
/ns 30 string def
x ns cvs
x scale mul dup 0 moveto ns show
neg 0 exch moveto ns show
1 1 x {
/y exch def
/nv 30 string def
x y mul nv cvs pop
x scale mul y neg scale mul moveto nv show
} for
} for
0 scale 2 div neg fs 2 div add moveto
scale n 1 add mul scale 2 div neg fs 2 div add lineto
scale 2 div fs 2 div add fs moveto
scale 2 div fs 2 div add scale n 1 add mul neg fs add lineto
stroke
showpage
Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.