官术网_书友最值得收藏!

  • Perl 6 Deep Dive
  • Andrew Shitov
  • 385字
  • 2021-07-03 00:05:48

Naming conventions

Perl 6 does not force the user to follow any specific naming conventions for variable names. Still, it is better to follow a general common sense approach. Variable names may be as short as one letter, but they can also be descriptive and contain many words.

Single-letter names are the best choice in loops, or in some calculations where all the mentions of the variable are located compactly and are clearly visible on the screen. Single-letter names, of course, may use both lower and uppercase letters. While there is no standard in Perl 6, the uppercase names are used for constants and pseudo-constants in the documentation; for example, check out https://docs.perl6.org/language/variables#Compile-time_variables.

Here are some examples of single-letter names:

constant $N = 100;
my $n = prompt('Enter a number: ');
say "You entered $n";
say 'This number is too big' if $n > $N;

For longer names, there are a few alternatives. Either you start with a small or capital letter, or the whole name is capitalized. Again, uppercase names such as $MAXIMUM are better to represent constants, even if you don't use the constant keyword. In general, lowercase names are preferable. Let's rewrite the previous program so that it uses longer variable names:

constant $MAXIMUM = 100;
my $value = prompt('Enter a number: ');
say "You entered $value";
say 'This number is too big' if $value > $MAXIMUM;

In many cases, even longer names are needed. In this case, there are a few ways to construct the name using two or more words. First, you can use the so-called camel case names, for example, $userValue or $valueFromInput. Second, the underscore character is a good candidate for concatenating parts of the name—$user_value or $value_from_input; this style is called snake case. Finally, Perl 6 allows extravagant names with dashes, for example, $user-value or $MAXIMUM-VALUE (kebab case). The - character is not a minus operator in this case, and is a part of the name. So, the $uservalue, $userValue, $user_value, and $user-value names are four different names. Consider the following code snippet:

constant $MAXIMUM-VALUE = 100;
my $entered-value = prompt('Enter a number: ');
say "You entered $entered-value";
say 'This number is too big'
if $entered-value > $MAXIMUM-VALUE;

Choose your own style and try to consistently use it throughout the program.

主站蜘蛛池模板: 东平县| 离岛区| 永定县| 成都市| 侯马市| 凤山市| 莲花县| 灵丘县| 西峡县| 黔南| 木兰县| 大足县| 隆德县| 柘城县| 西平县| 白朗县| 海兴县| 内乡县| 潢川县| 龙州县| 剑川县| 包头市| 如皋市| 都江堰市| 鄂尔多斯市| 资溪县| 西乌珠穆沁旗| 德安县| 襄城县| 曲阜市| 东兴市| 崇左市| 漳浦县| 信丰县| 宕昌县| 百色市| 安吉县| 辉南县| 长顺县| 济南市| 霸州市|