πŸ“˜ Camel case using Perl 6

πŸ“˜ Camel case using Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


Create a camel-case identifier from a given phrase.

It is a good practice to follow some pattern when choosing names for variables, functions, and classes in any programming language. In Perl 6, identifiers are case-sensitive, and, unlike many other languages, hyphens are allowed. So, variables names like $max-span or function names like celsius-to-fahrenheit are accepted.

In this task, we will form the CamelCase variable names from a given phrase. Names created in this style are built of several words; each of which starts with a capital letter.

Here’s the program that does the required conversions:

my $text = prompt('Enter short text > ');
my $CamelName = $text.comb(/\w+/).map({.lc.tc}).join('');
say $CamelName;

All the actions are done in a sequence of method calls. The words are selected from the input $text using the comb method with a regex /\w+/. Then, each found word is mapped using another chained method call: 

{ .lc.tc }

A β€˜bare’ dot means that the method is called on the default variable $_, which is repeatedly set to the current element. In Perl 6, there is no ucfirst method to make the first letter of the text uppercase. Instead, we use the tc method (tc stands for Title Case), and call it on the result of the lc call to make sure that after calling .lc.tc, all the letters are lowercase except the first one. Finally, the elements of the array are joined together with the help of the join method. The input string β€˜Hello, World!’ becomes HelloWord after all the transformations are done.

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code