[ EN | PT] Perl - Using conditionals (first part) | Perl - Usando condicionais (parte 1)

Read too on Odysee

English version

We finally come to the use of conditionals in Perl (the famous if and else).

If conditional

The basic if structure is like this:

if (condition) {
say "The condition is true";
}

This code means that, if the expression in the condition is true, the message "The condition is true" will be printed on the screen. If false, that entire block of code will be ignored. An example that can be evaluated is the following:

$age = 25;
if ($age >= 18) {
print "Authorized\n";
}

Where, if the variable $age is greater than or equal to 18, the message “authorized” will be written on the screen.

So, let's create a program for a supermarket that tells whether or not a person can buy alcohol and cigarettes. The person will say his age, and the system will say "purchase authorized" if he is at least 18 years old, and if he is not, the system will say "purchase not authorized". The first part of our system is already in our example, time to see how to capture the user's age.

Capturing user input

To keep things smooth, let's capture user input. This entry is captured by the <STDIN> command. Note the example:

print "What is your name?\n";
$nome = <STDIN>;
print "Your name is " . $nome . "\n";

And this is how you capture user input. However, if you've tested this code, you might have noticed one thing: there are two newlines instead of one. This might not be a problem for someone who just wants to print a word at the end of a line, but for anything else the variable is kind of useless. We can solve it with the chomp function:

print "What is your name?\n";
chomp($nome = <STDIN>);
print "Your name is " . $nome . "\n";

This removes the newline inserted by hitting enter when entering the value. Based on this, and on the fact that in Perl numbers and strings are read in the same way, we can change our code to use ages dynamically, which, in addition to allowing us to test our code with multiple values without making changes to it, also it is part of the functionalities that are necessary for our program to be complete.

If you've done everything right so far, your code should look like this:

chomp($age = <STDIN>);
if ($age >= 18) {
print "purchase authorized\n";
}

Else

But what if the purchase is not authorized? In this case, we will use another conditional: else. The structure syntax is as follows:

if (condition) {
say "the condition is true";
} else {
say "the condition is false";
}

Our code can be implemented in this case as follows:

chomp($age = <STDIN>);
if ($age >= 18) {
print "purchase authorized\n";
} else {
print "purchase not authorized\n"
}

And that's basically it. So, what do you think? Leave your answer in the comments 😆🥰

And follow me on Odysee too 😊

Exercises

Here are some exercises for you to fix your knowledge:

  1. Make a program that receives two values and prints the greater
  2. Make a program that receives a value and says whether it is positive or negative
  3. Write a program that receives three grades from a student. If the average between them is greater than or equal to 7, say that it is approved, otherwise say that it is disapproved

Leia na Odysee também

Versão em português

Chegamos finalmente ao uso de condicionais em Perl (os famosos if e else).

Condição if

A estrutura básica de um if é essa:

if (condicao) {
say "A condição é verdadeira";
}

Esse código significa que, caso a expressão em condicao seja verdadeira, a mensagem "A condição é verdadeira" vai ser impressa na tela. Caso seja falsa, esse bloco de código inteiro será ignorado. Um exemplo que pode ser avaliado é o seguinte:

$idade = 25;
if ($idade >= 18) {
print "Autorizado\n";
}

Onde, caso a variável $idade seja maior ou igual a 18, a mensagem “autorizado” será escrita na tela.

Vamos criar então um programa para um supermercado que diga se uma pessoa já pode ou não pode comprar álcool e cigarros. A pessoa dirá sua idade, e o sistema dirá "compra autorizada" caso ele tenha no mínimo 18 anos, e, caso não tenha, o sistema dirá "compra não autorizada". A primeira parte de nosso sistema já está em nosso exemplo, hora de ver como capturar a idade do usuário.

Capturando entrada de usuário

Para continuarmos com mais tranquilidade, vamos capturar entradas do usuário. Essa entrada é capturada pelo comando <STDIN>. Observe o exemplo:

print "Qual é seu nome?\n";
$nome = <STDIN>;
print "Seu nome é " . $nome . "\n";

E é assim que se captura uma entrada de usuário. Porém, se você testou esse código, você deve ter notado uma coisa: ocorrem duas quebras de linha ao invés de uma. Isso pode não ser um problema para quem só quer imprimir uma palavra no final de uma linha, mas para qualquer outro fim a variável é meio inútil. Podemos resolver com a função chomp:

print "Qual é seu nome?\n";
chomp($nome = <STDIN>);
print "seu nome é " . $nome . "\n";

Isso remove a linha nova inserida ao apertar enter quando se insere o valor. Baseado nisso, e no fato que em Perl os números e strings são lidos da mesma forma, podemos alterar nosso código para utilizar idades de forma dinâmica, o que, além de permitir que testemos com múltiplos valores o nosso código sem realizar alterações nele, também faz parte das funcionalidades que são necessárias para que nosso programa esteja completo.

Se você fez tudo certo até aqui, seu código deve se parecer com isso:

print "Digite sua idade:\n";
chomp($idade = <STDIN>);
if ($idade >= 18) {
print "Compra autorizada\n";
}

Else

Mas e se a compra não for autorizada? Nesse caso, teremos o uso de outra condicional: else. A sintaxe da estrutura é a seguinte:

if (condicao) {
say "condição verdadeira";
} else {
say "condição falsa";
}

Nosso código pode ser implementado nesse caso da seguinte forma:

print "Digite sua idade:\n";
chomp($idade = <STDIN>);
if ($idade >= 18) {
print "Compra autorizada\n";
} else {
print "Compra não autorizada\n";
}

E é basicamente isso. E aí, o que achou? Deixe sua resposta nos comentários 😆🥰

E me segue na Odysee também 😊

Exercícios de fixação

Separei aqui alguns exercícios para você fixar seus conhecimentos:

  1. Faça um programa que receba dois valores e imprima o maior
  2. Faça um programa que receba um valor e diga se é positivo ou negativo
  3. Faça um programa que receba as três notas de um aluno. Se a média entre elas for maior ou igual a 7, diga que ele está aprovado, senão diga que ele está reprovado

Coin Marketplace

STEEM 0.30
TRX 0.12
JST 0.032
BTC 61227.60
ETH 3022.96
USDT 1.00
SBD 3.88