WHILE and DO WHILE loopings in Perl - How to Use

In this Perl tutorial, we will start studying repetition statements, also called loops, starting with good old while and then getting to know the do while looping.

WHILE looping in Perl

The WHILE loop syntax is as follows:
while( expressiona ){
   # code to run
   # in case expression
   # be true
}
It works like this: we type while, we open parentheses and inside it we put some expression. It can be a value (such as a number, a boolean as true or false) or usually a condition, a conditional test whose result will be true or false.

If the final expression is true, the code inside the WHILE loop braces is executed.
At the end of each execution (we call each round of iteration execution), the expression is evaluated again.

If it remains true, the code continues to be ran and ran ...
The usual thing is that there is something inside the code that will eventually change the conditional test that is being performed so that it becomes false at some point and stops the while execution.

WHILE loops examples in Perl

First, let's learn how to count from 1 to 100 with the WHILE loop.
Let's use the $num variable to store numbers from 1 to 100, and print them on the screen.

The code looks like this:
#!/usr/bin/perl

$num=1;

while($num <= 100){
        print $num, "\n";
        $num++;
}    

First, we initialize the variable with the value 1.
The test we will do is: $num <= 100

In other words: is the variable less than or equal to 100? If so, run the code below ...

In code within the repetition statement, we print the variable.
Then we have to increment it by one, we do it with the operator: ++

Now the value of $num is 2. The while expression is evaluated again, and it will be true again. The code will execute, print, and increment ... and this will happen until $num is 100.

At this value, the test is still true, the print is performed, and when the variable is incremented it becomes 101. Then, in the next test of the while expression, the result will be false and the looping will end.

Let's now do the opposite, a countdown, displaying from 1000 to 1:
#!/usr/bin/perl

$num=1000;

while($num>0){
        print $num, "\n";
        $num--;
}    

Note that we now start with the value 1000, the test is "as long as it is greater than 0" and decrement the variable ($num--).

Awesome ! Powerful, this Perl, isn't it?

DO WHILE looping in Perl

The WHILE loop has a special feature: It only runs the first iteration if the expression in it is TRUE, if it is FALSE, the loop doesn't even begin.

If you want at least one iteration to occur, the test to be run at least once, we recommend using DO WHILE. Its structure is very similar to while:
do{
   # code tobe
   # executed
}while(condition);   

First it does the iteration (DO), only then tests the condition.
If it is true, rerun the code between the braces.

A great utility of the WHILE loop is to display menus.

Menus should be displayed at least once to the user, if they want to exit the program right away, ok, but they should be displayed at least once.

Let's look at an example of a banking app:
#!/usr/bin/perl

do{
        print "Choose an option:\n";
        print "0. Exit\n";
        print "1. Extract\n";
        print "2. Withdraw\n";
        print "3. Transfer\n\n";
        chomp($op = <STDIN>);
}while($op != 0);
We store the user option in the $op variable.

If he types 1, 2, or 3, something specific should happen (call the transfer options, go to the withdrawal screen, etc), then we'll see how to program this in Perl.

Then the menu is displayed again.
And it just stops showing if you type 0 to exit.

See the test: $op! = 0
This means: run this loop while the option is different from 0.

The following code asks for the password for the user.
If correct, it falls into the IF and we warn that it is entering the system.
If it goes wrong, it drops to ELSE and we warn it to try again:
#!/usr/bin/perl

do{
        print "Type the password:\n";
        chomp($password = <STDIN>);

        if($password eq 'rush2112'){
                print "Entering the system...\n";
        }else{
                print "Wrong password, try again.\n\n";
        }
}while($password ne 'rush2112');
Note that the condition is: as long as the password is not equal to "rush2112".

That is, the password is rush2112, if use does not enter the correct password, it will be stuck forever on this screen asking for password ... the only way to enter the system therefore is by entering the correct password.

Note that we place an IF ELSE conditional test inside a DO WHILE control structure, this is quite common in programming, tests and loopings being 'nested' to other flow control structures.

Let's now see how to print from 1 to 100 with DO WHILE:
#!/usr/bin/perl

$num=1;

do{
        print $num, "\n";
        
}while(++$num<=100);
Note the command: ++$num <= 100

This means that the $num variable is incremented at first (since the ++ symbol came before) and only after the variable is used for the conditional test.


Now do: $num++ <= 100
What happens to the result? Why?
Explain in the comments.

GIVEN and WHEN statements in Perl

In this tutorial from our Perl tutorial, we will learn how to use the given conditional test statemtns.

Statement GIVEN in Perl

If you have studied other programming languages, such as C, C ++, or Java, for example, you should be aware of the switch command, which works as a kind of IF and ELSE.

See our tutorial on IF, ELSIF and ELSE in Perl.

Study again the last example, on nested conditional tests statements, where we put several IF and ELSE inside other IF and ELSEs.

Basically, we have a value or expression, where we want to take its result and compare it against a series of possibilities and run a certain code specific to that result.

The given when syntax is as follows:
given (expression){
        when(value1) { #code in case
                       #expression = value1 
                     }
        when(value2) { #code in case
                       #expression = value2 
                     }
        when(value3) { #code in case
                       #expression = value3 
                     }
        default { #code in case
                  #expression be
                  #other value
                }
} 

How works GIVEN and WHEN in Perl

Let's give given some expression, such as a conditional test that results in some value, boolean or not, the information is expression.

Note that each when has a value in it, within the parentheses of each, Perl exits testing expression with all these values within when.

When it finds a value that matches expression, that is, they execute the code of that when.

If it doesn't find any when with a value that matches the given value, it executes the default code.

Usage examples of GIVEN and WHEN in Perl

The following code prompts the user for a number from 1 to 7 and prints the name of the day of the week in full on the screen. If you enter it wrong, it defaults to the problem.
#!/usr/bin/perl

use experimental qw( switch );

print "Week day: ";
chomp($day=<STDIN>);

given ($day){
        when(1) {print "Sunday\n";}
        when(2) {print "Monday\n";}
        when(3) {print "Tuesday\n";}
        when(4) {print "Wednesday\n";}
        when(5) {print "Thursday\n";}
        when(6) {print "Friday\n";}
        when(7) {print "Saturday\n";}
        default {print "Invalid day\n";}
}       

Note a few things.
First, this is possible to program with IF and ELSE, but with them it gets longer and messier.

Second, the GIVEN command is still experimental, in Perl, so for the time being, avoid using it whenever you can.

Let's create now a mini translator, where the user will type the color in English and we will display the translation, in Portuguese:
#!/usr/bin/perl

use experimental qw( switch );

print "Color: ";
chomp($color=<STDIN>);

given ($color){
        when("red") {print "Vermelho\n";}
        when("blue") {print "Azul\n";}
        when("yellow") {print "Amarelo\n";}
        when("Green") {print "Verde\n";}   
        default {print "Color not in database\n";}
}       

Awesome this Perl, isn't it?

Study references Perl

https://www.perlmonks.org/?node_id=1078449
https://www.perltutorial.org/perl-given/

UNLESS statement in Perl - How to use

In this tutorial of our Perl Course, we will learn what it is, what it is for, and how to use the unless conditional test in Perl.

unless in Perl

We saw in the IF conditional test statement tutorial that it executes a particular block of code if an expression or condition is true.

There is a selection structure contrary to IF, which is UNLESS, ie it will execute certain commands if the conditional test is FALSE.

That is, we use it like this:
unless (condition){
   # code in case
   # condition be false
}
That is, look at the logic of this structure: unless [test] is true, do ...
Now let's look at some examples.

How to use unless in Perl

Create a Perl script that prompts the user to join a party and only allows entry if they are 21 or older.
The script code is:
#!/usr/bin/perl

print "Age: ";
chomp($age=<STDIN>);

unless($age>=21){
        print "You must be 21 at least\n";
}
Now the logic should work well in your head, so you can understand the concept and be a good programmer. What this code means is:

  • print this message, unless the condition is true


That is, if the condition is false, it is to run the unless code.

It is to run, unless it is true, that is, if true does not run, only runs if it is false, unlike IF that only runs if true.
A little confusing at first, but take it easy.

unless and else einm Perl

And, as with our beloved IF and ELSE, there is also UNLESS and ELSE.

Well, if the test is true falls in IF and if false falls in ELSE, in the case of unless it is the opposite: if the test is false, falls in UNLESS and if true, falls in ELSE.

Let's program the previous script more complete:
#!/usr/bin/perl

print "Age: ";
chomp($age=<STDIN>);

unless($age>=18){
        print "You must be 21 ate least\n";
}else{
        print "Just enter!\n";
}
Ready, now if you are 21 or older, warns that you can enter.
If you are under 21, you warn that you cannot enter.

How to use unless

Let's now take the example of the script that asks the password for the user, if it is different from 'rush2112', warns that the hacker will be arrested. If true, warn that you are entering the system.

Here's how the code looks:
#!/usr/bin/perl

print "Type the password: ";
chomp($password=<STDIN>);

unless($password eq 'rush2112'){
        print "Wrong password! We got you, hacker...\n";
}else{
        print "Correct password, entering the system...\n";
}
Note that we use the string equality comparison operator, eq.
If it is false, ie if the password is different from 'rush2112', we say that we caught the hacker.

We could do the opposite, using the inequality (not equal) operator, see:
#!/usr/bin/perl

print "Type the password: ";
chomp($password=<STDIN>);

unless($password ne 'rush2112'){
        print "Correct password, entering the system...\n";
}else{
        print "Wrong password! We got you, hacker...\n";
}
That is, if it is not unequal, it is because the password equals is correct:
It is the opposite of the previous one, and UNLESS is always the opposite of IF.

See that there is no right or wrong, better or worse, code is like fingerprint, each has its own style, see what makes more sense to you.

I particularly still prefer to use IF.

You can even use UNLESS with ELSIF, see:
https://beginnersbook.com/2017/02/unless-elsif-else-statement-in-perl/

IF / ELSE e IF/ELSIF/ELSE in Perl

In this tutorial from our Perl course, we will learn how to use the control structures:

  • IF / ELSE
  • IF / ELSIF / ELSE


The IF and ELSE Control Structure

In our past tutorial on the IF conditional statement, we learned that this statement allows a certain piece of code (within the IF) to be executed only by a test, where an expression must result in the TRUE value.

However, the code only executes if the test is true.
What if it's false? This is where the ELSE command comes in.

The scope of this structure is:
if ( expressiona ){
   # code in case the expression
   # be true
}else{
   # code in case the expression
   # be false
}

IF and ELSE Example in Perl

Let's redo the exercise:

  • You have been hired to create a script for a nightclub. In it, you ask the age of the person and if he is 21 or older, warns that he can enter.


Let's add an else command, which fires when the person is under 18, here's how it looks:
#!/usr/bin/perl

print "Type your age: ";
chomp($age=<STDIN>);

if($age>=21){
    print "You can come in\n";
}else{
    print "You can't come in\n";
}
Before, a message would only appear to the user if he was in adulthood, because he entered the IF.
Now if he is a minor, he will fall into ELSE and we will display another message.
Note that we now have greater 'control' over the execution flow of our Perl scripts.

Let's redo the other exercise:

  • You have to create a snippet of code where you will be prompted for a password for the user, and will allow them to enter the system only if they enter the correct password, which is rush2112.


#!/usr/bin/perl

print "Type your password: ";
chomp($password=<STDIN>);

if($password eq 'rush2112'){
    print "Password correct, entering in the system...\n";
}else{
    print "Word password! Intruder detected!\n";
}
If you wrog the password, the script will catch you!

Nested IF and ELSE

A very common technique in programming is to use conditional statements within other conditional statements. Let's create a script that takes two numbers and says which is the largest and the smallest, or if they are equal.

First, we test if $a is greater $b, if it is, ok, it falls in the first IF and ends.
If it is not, it will fall into the ELSE.

In this ELSE, we already know that $a is not greater than $b, so it is either equal or $b is greater than $a.

Now, inside ELSE, let's use another structure, an IF asking if $b is greater than $a.
If so, warns you and terminates the program.

If $b is not greater than $a (and $a is no longer than $b), then they are equal numbers, and that possibility falls into an ELSE internal to the first ELSE.

Here's how the code looks:
#!/usr/bin/perl

print "First number  : ";
chomp($a=<STDIN>);

print "Second number : ";
chomp($b=<STDIN>);

if($a > $b){
    print "$a is greater than $b\n";
}else{
    if($b > $a){
        print "$b is greater than $a\n";
    }else{
        print "$a is equal to $b\n";
    }
}
IF can exist on its own, as we saw in the last tutorial.
But for each ELSE, there is its IF.

We put the code well indented, that is, spaced so that we see the pairs of IF and ELSE.

IF / ELSIF / ELSE

Create a program that asks the user for a score from 0 to 10.
If it is 9 or older, say that he has scored A.
If you are 8 to 9, say you got a grade B.
If it's 7 to 6, say you got a grade C.
If it's 6 to 7, say you got a grade D.
Below 6 marks F.

First, we test whether the grade is greater than or equal to nine. If it is, we give A.
If it's not greater than or equal to 9, it's because it's less than 9, so let's test if it's greater than 8, if it's got a grade B.

If it is not, it is below 8.
We now test if it is greater than 7, if it is grade C.

If it is not greater than 7, it is smaller. So we test if it is greater than 6, if it is we say it got a grade D.
Finally, if it does not fall in any of the above cases, it falls in the final ELSE and we say it scored F because it scored less than 6.

Here's how the code looks:
#!/usr/bin/perl

print "Your grade: ";
chomp($grade=<STDIN>);

if($grade>=9){
    print "Score A.\n"
}else{
    if($grade>=8){
        print "Score B\n";
    }else{
        if($grade>=7){
            print "Score C\n";
        }else{
            if($grade>=6){
                print "Score D\n";
            }else{
                print "Score F\n";
            }
        }
    }
}
Notice how it goes 'breaking' and going to the right.
In a larger and more complex script, this gets horribly ugly.

Note that the excerpt: else {if ... happens more than once.
We can abbreviate these lines to simply: elsif (expression)

Let's see how our code looks like using ELSIF:
#!/usr/bin/perl

print "Your grade: ";
chomp($grade=<STDIN>);

if($grade>=9){
        print "Score A.\n"
}elsif($grade>=8){
        print "Score B\n";
}elsif($grade>=7){
        print "Score C\n";
}elsif($grade>=6){
        print "Score D\n";
}else{
        print "Score F\n";
}
Much nicer to see, understand and organized, don't you agree?

IF statement in Perl

Now that we've learned the comparison operators in Perl, let's start our studies on control structures, starting with the IF conditional test.

IF statement in Perl

The IF command is said to be a selection structure because it is a command that allows a certain action to be selected or not. That is, with the use of IF, some things are executed and some not, all depending on conditional tests that we will do.
if( test ){
   # code in case the test
   # be true or 1
}
It works like this, first type if, then we open parentheses and inside it must have something that is true (1) or false (empty), we usually put a conditional test statement, that is, a comparison, which we study in the last tutorial of our course. Perl

Then we open braces: {}

If the conditional test is true, everything within these keys will be executed.
If the test is false, the IF command is simply ignored, perl skips it as if it did not exist.

What happens here is decision making. Perl evaluates whether the value is true or false and decides to execute a certain block of code or not.
How to use IF statement in Perl

Let's see how this works in practice?

Example of using IF in Perl

You have been hired to create a script for a nightclub. In it, you ask the age of the person and if he is 21 or older, warns that he can enter.

Let's store the person's age in the $age variable and ask for their age via <STDIN>.
Now we need to compare $ age with 18 to find out if it is greater than or equal to:

  • $ age >= 21

Just put this in parentheses of IF.
Inside if, we only give a print warning that the person is bigger and can enter, see how our code was:
#!/usr/bin/perl

print "Tye your age: ";
chomp($age=<STDIN>);

if($age>=18){
    print "You can come in\n";
}

How to use IF in strings in Perl

You have to create a snippet of code where you will be prompted for a password for the user, and will allow them to enter the system only if they enter the correct password, which is rush2112.

We will store the password in the $password variable and compare it with the string 'rush2112', if it is the same, enter the IF code and say it will enter the system, our code looks like this:
#!/usr/bin/perl

print "Type your password: ";
chomp($password=<STDIN>);

if($password eq 'rush2112'){
    print "Correct password, entering in the system...\n";
}

What if you enter the wrong password? It does not fall within the IF code, so it does not enter the system, simple as that.

Boolean Values in Perl

In fact, it does not have to be a conditional test, the important thing is to result in a boolean value:

  • True, true or 1
  • False, false, empty or 0

The following IF will always be executed:
#!/usr/bin/perl

if(1){
    print "This IF always runs.";
}
The following IF, only programmers can see what's inside it, as it will never run:
#!/usr/bin/perl

if(0){
    print "Only Perl Programmers Can Read This.";
}
'Read the code': if true, execute the code below ...
Makes sense, doesn't it?

Note that now our scripts don't always work the same way as before ... they depend, they rely on a conditional test. We now have greater control over our little Perl programs.

Comparison Operators in Perl

Now that we've studied the basics of Perl, let's learn more complex things that will make our scripts even more interesting and useful.

Let's learn how to compare numbers and strings in this Perl tutorial.

Numerical Comparison Operators in Perl

There are 6 comparison operators, which we can use with numbers, in Perl, and they are quite simple as they look like the ones we use in math.

The operators are:
  1. Equal: ==
  2. Not equal: !=
  3. Greater than: >
  4. Less than: <
  5. Greater than or equal to : >=
  6. Less than or equal to: <=
We use them like this:

  • value1 operator value2

And this operation always returns 1 (TRUE ) or empty (FALSE or 0).

For example, run the following script:
#!/usr/bin/perl

print "2==2: ",2==2,"\n";
He will return: 1
What print does is the result of operation 2 == 2

This operation is a comparison operation, you're asking: 2 equals 2?
He answers truthfully (represented by 1).

Now test this:
#!/usr/bin/perl

print "2==2: ",2==2,"\n";
print "1>2 : ",1>2,"\n";
The result is:
2 == 2: 1
1> 2:

When asked if 1 is greater than 2, it responds with empty, nothing, null ... which is the same as false in Perl.

What if we ask if 1 is different from 2?
We do this with: 1! = 2, and it's a true statement, test the script:
#!/usr/bin/perl

print "2==2: ",2==2,"\n";
print "1>2 : ",1>2,"\n";
print "1!=2: ",1!=2,"\n";
Everything worked?

The operation: $ a <$ b
Returns true (1) if $a is less than $b, and false if  a is greater than or even equal to $b.

Already the expression:
$a >= $b
Returns true (1) if $a is greater than or equal to $b and returns false (null) if $a is less than $b.

Finally, the operation:
$a <= $b
Returns 1 if $a is smaller or if $a is equal to $b. If $a is greater than $b it returns false (null).

Perl string comparisons

To compare strings, we will use some small letters, which represent the same thing as the operators above:

  1. Equal to: eq
  2. Not equal to: ne
  3. Greater than: gt
  4. Less than: lt
  5. Greater than or equal to: ge
  6. Less than or equal to: le

That is, the string comparison operators in Perl are:
eq (equal), ne (not equal), gt (greater than), lt (less than), ge (greater than or equal to) and le (less than or equal to).

The comparison is done character by character one by one, comparing to know if the strings are equal or not.

Let's look at some examples:
#!/usr/bin/perl

print "rush eq rush: ", 'rush' eq 'rush',"\n";
print "rush ne Rush: ",'rush' ne 'Rush',"\n";
print "abc gt ab   : ",'abc' gt 'ab',"\n";
print "bc lt bcd   : ",'bc' lt 'bcd',"\n";
Note that in the ASCII standard, uppercase letters come before lowercase:
#!/usr/bin/perl

print "A lt a: ", 'A' lt 'a',"\n";
print "b gt B: ",'B' ne 'b',"\n";
That is, 'A' is less than 'a'
And 'b' is bigger than 'B'

Test the scripts, guys. See the results.
All these operations are like 'questions' to Perl, which answers 1 or null, that is, true or false.

And be careful not to confuse:
$a == 1: is a comparison, is a question '$a equals 1?', generates true or false return

And:
$a = 1: it's an assignment, $a will get the value 1 and period, it's over there.

Basic Perl Exercises (solved and commented)

Perl Exercises

1. Create a script that asks the user for a number and shows the double.

2. Create a script that prompts the user for a number and displays its square.

3. Create a script that asks for the radius of a circle and displays the diameter, length of the circle, and the area of the circle.

4. Create a Perl script that prompts the user for two grades and displays the average.

5. Do the same as the previous exercise, but with 3 notes.

6. Make a script that simulates a calculator in Perl. It should prompt the user for two numbers and then display the result of the sum, subtraction, multiplication, division, average and the remainder of the division of the first by the second.

7. Create two scripts, one that takes the temperature in Celsius and converts it to Fahrenheit, and one that does the opposite. The mathematical formulas are:

Converter Fahrenheit para Celsius em Perl


  • !!! ATTENTION !!!
Guys, below have the solutions.
But I strongly suggest that you try to solve the above questions, try hard, think, research, try again ... if you make a mistake or the code comes out ugly and big, no problem, IT'S SAME at the beginning!

It's part of the journey!

Insist, break your head, this is how you become a good programmer and not watching Youtube videos of people programming, learn is really trying, the good ones are forged like this, in the race, in the attempt, ok?

Below, the solutions.

Commented Solutions in Perl

1.
#!/usr/bin/perl

print "Number: ";
$num = <STDIN>;
chomp($num);
print "Double: ",2*$num, "\n";
2.
#!/usr/bin/perl

print "Number: ";
$num = <STDIN>;
chomp($num);
print "Square: ",$num*$num, "\n";
3. The diameter formula is twice the radius, let's store the radius in the $rad variable.
In length is: 2 x pi x radius, which in Perl is: 2 * 3.14 * $rad
Area formula: pi x radius² = 3.14 * $ rad * $ rad
#!/usr/bin/perl

print "Radius: ";
$rad = <STDIN>;
chomp($rad);
print "Diameter: ", 2*$rad, "\n";
print "Length  : ", 2*3.14*$rad, "\n";
print "Area    : ", 3.14*$rad*$rad, "\n";

4. Let's store the grades in the $num1 and $num2 variables.

The average formula is: ($num1 + $num2)/2

Be careful to not to do: $num1 + $ num2 / 2, if you do, by the operator precedence rule, the division will be done first, in the $num2 variable, and then the sum, doing the wrong calculation.

To make no mistake and leave the code well organized, use parentheses, ok?
#!/usr/bin/perl

print "Grade 1: ";
$num1 = <STDIN>;
print "Grade 2: ";
$num2 = <STDIN>;

chomp($num1);
chomp($num2);

$media = ($num1 + $num2)/2;
print "Average: ",$media, "\n";
Can you do it using fewer variables?
5.
#!/usr/bin/perl

print "Grade 1: ";
$num1 = <STDIN>;
print "Grade 2: ";$num2 = <STDIN>;
print "Grade 3: ";$num3 = <STDIN>;

chomp($num1);
chomp($num2);
chomp($num3);

$media = ($num1 + $num2 + $num3)/3;
print "Average: ",$media, "\n";
6.
#!/usr/bin/perl

print "First  : ";
$num1 = <STDIN>;
print "Second : ";
$num2 = <STDIN>;

chomp($num1);
chomp($num2);

print "Sum           : ",$num1+$num2, "\n";
print "Subtraction   : ",$num1-$num2, "\n";
print "Multiplication: ",$num1*$num2, "\n";
print "Division      : ",$num1/$num2, "\n";
print "Average       : ",($num1+$num2)/2, "\n";
print "Remainde      : ",$num1%$num2, "\n";
7.

Celsius to Fahrenheit:
#!/usr/bin/perl

print "Degrees in Celsius: ";
$C = <STDIN>;
chomp($C);

$F = (9*$C/5) + 32;

print "Degrees in Fahrenheit: ",$F, "\n";
Fahrenheit to Celsius:
#!/usr/bin/perl

print "Fahrenheit: ";
$F = <STDIN>;
chomp($F);

$C = 5*($F-32)/9;

print "Celsius: ",$C, "\n";

Receiving User Data: < STDIN > and chomp

In this tutorial of our Perl course, we will learn how to receive user keyboard data through the <STDIN> operator and the chomp function.

Perl programming interactivity

So far, our scripts have always worked a certain way, always repeating the same, and always resulting in the same things (printing information on the screen).

But is this what happens in most of the programs we use?
Let's think a little.

If you click on a song, your player plays it.
If you click on another one, it will run another song.

If you join your social network, some information appears.
If someone else logs in, different things will appear.

If you type a certain URL, you go to a website.
If you type another, go to another site.

That is, programs, scripts, and systems react differently depending on the information they receive from the user. There is an interactivity, the machine does a certain thing if you do a certain action.

Receiving User Information in Perl: <STDIN>

Let's have the person who will use our Perl scripts provide data, information to the program.

First, let's take this information from the user's keyboard (other ways can be used, such as taking data from an internet form, a file from your machine, a particular location on the screen that the person clicked on, etc etc).

Let's do this through the <STDIN> operator.
To store a keyboard entry and store it in the $ my_variable variable, we do:

  • $ my_variable = <STDIN>;


Run the script through the command terminal.
Note that first it displays the first print of the script, then nothing happens in the program.

This is because Perl has arrived at <STDIN> (standard input) and it is waiting for the user to type in something and press ENTER.

Enter "Progressive Perl Course".
Then it prints the variable on the screen, which stores what you typed, see the result:
How to use <STDIN> in Perl

Perl's chomp function

Let's create a script that asks the user for data, a number, for example, and then prints it on the screen:
#!/usr/bin/perl

print "Type a number: ";
$num = <STDIN>;
print "You wrote: $num";
Note a curious thing, after printing the number on the screen, there is a line break:
Perl standard input <STDIN>

But there is no \n character in the script, so why?

What happens after we enter the number?
We hit enter.

So the $num variable doesn't just have "2112" stored.
It actually has "2112\n" with the line break, because you hit enter.

However, we don't always want this thing in the end. If we are going to work with numbers, for example, we just want 2112 and no \ n, do you agree?

So, that's where the chomp() function comes in.
Just put the variable inside the parentheses and this function will take \n.

Here's how the code looks using the chomp () function:
#!/usr/bin/perl

print "Type a number: ";
$num = <STDIN>;
chomp($num);
print "You wrote: $num";

And the result:
How to program in Perl

Now yes, we only have the number stored in the $num variable!
We can even take an even bigger tug at our code:
#!/usr/bin/perl

print "Type a number: ";
chomp($num = <STDIN>);
print "You wrote: $num";

Damn! This Perl is amazing!

Exercise

Download and install Visual Studio Code.
Create a file "progerssiveperl.pl", put the scripts of this tutorial, go to "Terminal -> Run Active File", did your code run ok?