This is the first part of the first perl weekly challenge.
I haven't looked at the other solutions that have been published, but I'm pretty sure they'll go along these lines, at least in Perl 6.
Here's the challenge:
Write a script to replace the character ‘e’ with ‘E’ in the string ‘Perl Weekly Challenge’. Also print the number of times the character ‘e’ is found in the string.
This was easy and almost straight out of the Perl 6 documentation: StrDistance
.
my $changes = (my $pwc = ‘Perl Weekly Challenge’) ~~ tr/e/E/;
say $pwc;
say +$changes;
It could be golfed, but also ungolfed. Basic trick here is that I'm defining a variable $pwc
on the fly so that I can apply tr
to it. I could use .trans
, because in Perls there is always more than one way to do it, but then I couldn't get the secondary effect of counting changes. I can do that with tr, which has the (Rakudo-only, whatever that means, because there's only one Perl 6 compiler, and that's Rakudo) nice secondary effect of returning an StrDistance
object that can, in number context, return the number of changes. That's why we hold the changed string in $pwc
and the change object in $changes. The last line is number-contextualized by putting a +
in front.
You want to get your chops in any of the Perls, head to https://perlweeklychallenge.org and start coding!
Top comments (1)
Here's Perl5 one-liner