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

  • Perl 6 Deep Dive
  • Andrew Shitov
  • 430字
  • 2021-07-03 00:05:46

One-line comments

One-line comments are separated from the program source code with the # character. Everything after the # symbol is skipped by the compiler until the end of the current line.

In the following example, we take the 'Hello, World!' program from Chapter 1, What is Perl 6?, and add a one-line comment to it:

say 'Hello, World!'; # Prints 'Hello, World!'

This is a fully correct Perl 6 program. It has one call of the built-in say function and a comment about what it does. The part of the string, starting from the # character, is a one-line comment.

If you run that program, it prints Hello, World! and nothing more. It works exactly the same as the program with no comments at all.

One-line comments may also occupy a separate line of code. For example, let's add more comments to the same program:

# This is a program in Perl 6.
# It prints the 'Hello, World!' string.
# To run it, install Rakudo Star and 
# run it from the command-line:
# perl6 ./hello.pl
 
say 'Hello, World!'; # it prints the string
 
# The program ends here.

This is also a completely valid Perl 6 program. From the perspective of business logic, the program did not change, as with the previous example, but from the perspective of future maintenance, it became much better as it explains what it does.

Another common practice of using one-line comments is to temporarily hide pieces of code. For example, during the debugging process, you want to disable some actions. Instead of removing the line of code, you can comment it out by adding the # character at the beginning of the line. Consider the following lines of code as an example:

say 'Hello, World!';
# print "Hello, World!\n";

Sometimes, you do the opposite—you add additional printing instructions to the program to see the values of different variables, and comment those instructions before making the code production-ready.

Here is an example of how you print the values that were passed to the function. I have used the addition example from Chapter 1, What is Perl 6?:

sub add($x, $y) {
say "x = $x, y = $y";
return $x + $y;
}

say add(4, 5); # 9

This program simply prints the result of the addition, but if you uncomment the first line of the subroutine code, it will also print the values of the $x and $y variables in a human-readable format which is shown in the following code:

x = 4, y = 5
9
主站蜘蛛池模板: 盱眙县| 宜兰县| 全州县| 白水县| 聂拉木县| 治县。| 敦煌市| 襄汾县| 焦作市| 久治县| 临颍县| 平南县| 米林县| 凤城市| 区。| 兴安盟| 长岛县| 子洲县| 平乡县| 苏尼特右旗| 正宁县| 瑞昌市| 武夷山市| 南江县| 荔浦县| 泰来县| 津南区| 天祝| 巴彦淖尔市| 句容市| 潜山县| 平定县| 泸州市| 康定县| 驻马店市| 繁昌县| 苍南县| 溧水县| 宁河县| 淄博市| 白河县|