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

  • Perl 6 Deep Dive
  • Andrew Shitov
  • 417字
  • 2021-07-03 00:05:47

Simple input and output

In the previous examples, we used the built-in print and say functions to print something to the console (speaking more strictly, to the standard output attached to the program). In this section, you will learn how to perform basic reading from the standard input. This is basically how the program gets what you type onto the console.

To read the input, there are a few functions that you may use directly without loading any modules. They are listed in the following table:

 

The get and line functions may be used when you need to parse the input data line by line. For example, call get as many times as you need if you know the structure of the input, or create a loop and iterate over the array that is returned by lines.

The slurp function does the job in one go. You can use it, for example, to copy everything from input to output. This is the program that does that:

print slurp;

There is another useful function: prompt. Use it to make two actions at once: the function prints a text message on the screen and returns the string that the user entered. This function blocks the execution of a program until the user finishes the input with a new line.

Let's demonstrate the work of the prompt function on an example program that calculates the circumference of a circle. The following program requests the radius from the user and then prints the result.

say 'The circumference is ', 
tau * prompt 'Enter the radius > ';

The program first prints the prompt message Enter the radius > and waits until the user types a number and presses the Enter key. Then, the say function prints another message, The circumference is, and appends the value that it gets after multiplying the input value by τ, which, as we've seen in the Using Unicode section of this chapter, equates to . We can see that in the following code:

$ perl6 circumference.pl
Enter the radius > 12
The circumference is 75.398223686155

We intentionally did not introduce any variables (we'll talk about them later in Chapter 3, Working with Variables and Built-in Data Types). Notice that the actual output happens from right to left: first, the message from prompt, then the text printed by say.

More sophisticated input and output, as well as working with files, are discussed in Chapter 9, Input and Output.

主站蜘蛛池模板: 汨罗市| 得荣县| 法库县| 五大连池市| 榆社县| 淳安县| 新乡县| 双辽市| 广宗县| 洛隆县| 渝中区| 澄迈县| 宜阳县| 行唐县| 班戈县| 沭阳县| 吴忠市| 思南县| 大田县| 容城县| 阳西县| 桐乡市| 湾仔区| 定陶县| 长宁区| 福安市| 昭觉县| 马关县| 苏尼特右旗| 简阳市| 芜湖县| 郸城县| 乌鲁木齐县| 汉川市| 萨迦县| 吉木萨尔县| 新晃| 灌云县| 桂东县| 依安县| 调兵山市|