EN | PT] Perl - Using conditionals (second part) | Perl - Usando condicionais (parte 2)

Read too on Odysee

Read the first part

Ok, you must be thinking now “OK, but why did this tutorial have a part 2?”, and I answer you: Perl has more conditional structures than just if and else. One such structure is unless.

See for example the unless command. The unless statement is a conditional structure similar to the if statement, but with inverted logic. It is used to test a condition, and if it is false, the code inside the unless block will be executed. For example:

unless (0) {
    print "Entered inside the unless\n";
}

Remembering that the number zero is interpreted by many languages, including Perl, as false, and the number one as true. In this case, as the conditional has a false value, the code inside the block will be executed.

Let's do a simple example: transform the example from the previous tutorial into an example of using unless. Let's start by recalling the given example, which is code for a program to see if a person can buy cigarettes or alcohol based on their age:

print "Enter your age:\n";
chomp($idade = <STDIN>);

if ($idade >= 18) {
    print "Purchase authorized\n";
} else {
    print "Purchase not authorized\n";
}

Now let's change the order using the unless conditional:

print "Enter your age:\n";
chomp($idade = <STDIN>);

unless ($idade < 18) {
    print "Purchase not authorized\n";
} else {
    print "Purchase authorized\n";
}

As you can see, the order of the factors has changed without necessarily changing the functionality of the code. That's basically how unless works, and although it's not a clause you'll often find in code, it's good to know more about this conditional structure.

Wassup did you like it? Tell me more in the comments 😄😊

Addendum

User @gwajnberg from Hive said something very important in the last tutorial which was the use of use strict; and use warnings; in his codes. I've omitted these elements throughout the examples, but it's really important that they be taken into account.

Use strict in your code, in short, will force you to write code using a more specific coding style, and will throw an error if you don't. This basically serves to prevent common errors at runtime from happening.

Meanwhile, use warnings basically serves to show possible typos, syntax errors or use of something that doesn't exist. The main difference between both is that the first terminates the program if it has an error and the second does not.

I won't go into much detail about how they both work because these are details that an absolute beginner would hardly understand, but it's important to mention that it's a good practice to always use these two tools in your codes.

To use them in your code, just put them in the first few lines before the code itself starts:

use strict;
use warnings;

print "Enter your age:\n";
chomp($idade = <STDIN>);

unless ($idade < 18) {
    print "Purchase not authorized\n";
} else {
    print "Purchase authorized\n";
}

If your code still has a hashbang at the beginning, just put it after it:

use strict;
use warnings;

print "Enter your age:\n";
chomp($idade = <STDIN>);

unless ($idade < 18) {
    print "Purchase not authorized\n";
} else {
    print "Purchase authorized\n";
}

And that’s it.

Exercises

  1. Write a Perl script that checks whether a number the user passes is even. If it is even, print “This number is even”, while if it is odd, print “This number is odd
  2. Research the length function and write a program that returns the message "Word too short" if a returned word has less than five letters
  3. Take your previous code and add use strict and use warnings. Did an error appear? How did you go about solving it?

Leia também na Odysee

Leia a parte 1

Ok, você deve estar pensando agora “tá, mas por que esse tutorial teve uma parte 2?”, e eu te respondo: Perl possui mais estruturas condicionais que apenas if e else. Uma dessas estruturas é a unless.

Veja por exemplo o comando unless. O comando unless é uma estrutura condicional parecida com o comando if, mas com a lógica invertida. Ele é usado para testar uma condição e, se ela for falsa, o código dentro do bloco unless será executado. Por exemplo:

unless (0) {
    print "Entrou dentro do unless\n";
}

Lembrando que o número zero é interpretado por muitas linguagens, inclusive Perl, como falso, e o número um como verdadeiro. Nesse caso, como a condicional tem valor falso, o código de dentro do bloco será executado.

Vamos fazer um exemplo simples: transformar o exemplo do tutorial anterior em um exemplo do uso de unless. Comecemos relembrando o exemplo dado, que é um código de um programa para ver se uma pessoa pode comprar cigarros ou álcool baseado em sua idade:

print "Digite sua idade:\n";
chomp($idade = <STDIN>);

if ($idade >= 18) {
    print "Compra autorizada\n";
} else {
    print "Compra não autorizada\n";
}

Agora vamos alterar a ordem usando a condicional unless:

print "Digite sua idade:\n";
chomp($idade = <STDIN>);

unless ($idade < 18) {
    print "Compra não autorizada\n";
} else {
    print "Compra autorizada\n";
}

Como pode ver, a ordem dos fatores foi alterada sem que a funcionalidade do código fosse necessariamente alterada. Esse é basicamente o funcionamento de unless, e, embora não seja uma cláusula usual de ser encontrada em códigos, é bom conhecer mais essa estrutura condicional.

E aí, gostou? Conta mais pra mim nos comentários 😄😊

Adendo

O usuário @gwajnberg da Hive falou algo muito importante no tutorial passado que foi o uso de use strict; e use warnings; em seus códigos. Eu omiti esses elementos durante os exemplos, mas realmente é importante que sejam levados em consideração.

O use strict no seu código, de forma resumida, fará que você seja obrigado a escrever o código usando um estilo mais específico de codificação, e acusará erro caso não o faça. Isso serve basicamente para evitar que erros comuns em tempo de execução possam acontecer.

Enquanto isso, o use warnings serve para basicamente mostrar possíveis erros de digitação, de sintaxe ou uso de alguma coisa que não existe. A principal diferença entre ambos é que o primeiro encerra o programa se tiver um erro e o segundo não.

Não vou entrar em muitos detalhes sobre o funcionamento de ambos porque se trata de detalhes que um iniciante absoluto dificilmente compreenderia, mas é importante mencionar que se trata de uma boa prática sempre usar essas duas ferramentas em seus códigos.

Para usar elas em seu código, é só colocar nas primeiras linhas antes do código em si iniciar:

use strict;
use warnings;

print "Digite sua idade:\n";
chomp($idade = <STDIN>);

unless ($idade < 18) {
    print "Compra não autorizada\n";
} else {
    print "Compra autorizada\n";
}

Se seu código ainda tiver uma hashbang no início, é só colocar depois dela:

#!/usr/bin/perl
use strict;
use warnings;

print "Digite sua idade:\n";
chomp($idade = <STDIN>);

unless ($idade < 18) {
    print "Compra não autorizada\n";
} else {
    print "Compra autorizada\n";
}

E é isso.

Exercícios

  1. Escreva um script Perl que verifica se um número que o usuário passar é par. Se for par, mostre “Esse número é par”, enquanto se for ímpar diga “este número é ímpar
  2. Pesquise sobre a função length e escreva um programa que retorne a mensagem “Palavra curta demais” caso uma palavra retornada tenha menos de cinco letras
  3. Pegue seus códigos anteriores e adicione use strict e use warnings. Apareceu algum erro? Como você fez para resolver?

Coin Marketplace

STEEM 0.29
TRX 0.12
JST 0.033
BTC 63373.75
ETH 3170.63
USDT 1.00
SBD 3.88