Introdução aos comandos Perl

Perl é uma linguagem de programação. Anteriormente, projetado apenas para edição de texto, agora é usado para muitos propósitos, como administração de sistemas no Linux, desenvolvimento web, programação de rede etc. O principal arquiteto e criador do Perl é Larry Wall. Foi criado em 1987 e ainda é usado como uma das principais linguagens de programação. Perl é uma linguagem de alto nível. É também uma linguagem de programação dinâmica e interpretada. Agora vamos aprender os comandos Perl em detalhes.

Comandos Perl básicos

1. Comando Perl básico para imprimir em Perl

#!/usr/bin/perl
# This will print "Hello, World"
print "Hello, world\n";

2. Comentário de linha única em Perl

#!/usr/bin/perl
# This is a single line comment
print "Hello Perl\n";

3. Comentário de várias linhas no Perl

#!/usr/bin/perl
=begin comment
This is a multiline comment.
Line 1
Line 2
Line 3
We can insert
as much lines
as comments
until we code =cut
to end multiline comments
=cut
print "Hello Perl\n";

4. Atribuição de variáveis ​​em Perl (interpolação de variáveis ​​com aspas duplas)

#!/usr/bin/perl
$a = 10;
print "Variable a = $a\n";

5. Caractere de escape no Perl

#!/usr/bin/perl
$a = "This is \"Perl\"";
print "$a\n";
print "\$a\n";

6. No Perl, as strings têm um comportamento diferente com aspas duplas e aspas simples. Enquanto aspas duplas permitem interpolação, aspas simples não.

#!/usr/bin/perl
# Interpolation example.
$str = "Hello \nPerl";
print "$str\n";
# Non-interpolation example.
$str = 'Hello \nPerl';
print "$str\n";

7. Maiúscula no comando Perl

#!/usr/bin/perl
# Only u will become upper case.
$str = "\uhello perl";
print "$str\n";
# All the letters will become Uppercase.
$str = "\Uhello perl";
print "$str\n";
# A portion of string will become Uppercase.
$str = "hello \Uperl\E";
print "$str\n";

8. Atribuição de variável escalar em Perl

#!/usr/bin/perl
$age = 35; # Assigning an integer
$name = "Tony Stark"; # Assigning a string
$pi = 3.14; # Assigning a floating point
print "Age = $age\n";
print "Name = $name\n";
print "Pi = $pi\n";

9. Operações escalares simples em Perl

#!/usr/bin/perl
$constr = "hi" . "perl";# Concatenates two or more strings.
$add = 40 + 10; # addition of two numbers.
$prod = 4 * 51;# multiplication of two numbers.
$connumstr = $constr . $add;# concatenation of string and number.
print "str = $constr\n";
print "num = $add\n";
print "mul = $prod\n";
print "mix = $connumstr\n";

10. Literais especiais em Perl

#!/usr/bin/perl
print "Current file name ". __FILENAME__ . "\n";
print "Current Line Number " . __LINENO__ ."\n";
print "Current Package " . __PACKAGENAME__ ."\n";
# here they cannot be interpolated
print "__FILENAME__ __LINENO__ __PACKAGENAME__\n";

Comandos Perl intermediários

1. Matrizes em Perl

O índice da matriz começa em 0. O índice negativo indica elementos da última posição. Exemplo abaixo.

#!/usr/bin/perl

@weekday = qw/Mon Tue Wed Thu Fri Sat Sun/;

print "$weekday(0)\n";
print "$weekday(1)\n";
print "$weekday(2)\n";
print "$weekday(6)\n";
print "$weekday(-1)\n";
print "$weekday(-6)\n";

2. Matrizes para elementos em uma sequência

#!/usr/bin/perl
@oneToTen = (1..10);
@fiftyToSeventyfive = (50..75);
@aToZ = (a..z);
print "@oneToTen\n"; # Prints one to ten
print "@fiftyToSeventyfive\n"; # Prints fifty to seventy five
print "@aToZ\n"; # Prints from a to z

3. Adição e remoção de elementos de matriz

#!/usr/bin/perl
# creating an array
@expression = ("happy", "sad", "angry");
print "1. \@expression = @expression\n";
# add element to the end of the arraypush(@expression, "jolly");
print "2. \@expression = @expression\n";
# add element to the beginning of the arrayunshift(@expression, "excited");
print "3. \@expression = @expression\n";
# remove element to the last of the array.pop(@expression);
print "4. \@expression = @expression\n";
# remove element from the beginning of the array.shift(@expression);
print "5. \@expression = @expression\n";

4. Hashes em Perl

Hash é um conceito de par de valor-chave. Abaixo está um exemplo para criar um hash.

#!/usr/bin/perl
%data = ('Mohan Singh' => 55, 'Ram Gupta' => 25, 'Bhuvan Kumar' => 31);
@age = values %data;
print "$age(0)\n";
print "$age(1)\n";
print "$age(2)\n";

5. Adição e remoção do elemento hash

#!/usr/bin/perl
%data = ('Mohan Singh' => 55, 'Ram Gupta' => 25, 'Bhuvan Kumar' => 31);
@keys = keys %data;
$size = @keys;
print "a - Hash size: $size\n";
# add an element to the hash;
$data('Imran Khan') = 44;
@keys = keys %data;
$size = @keys;
print "b - Hash size: $size\n";
# delete an element from the hash;
delete $data('Imran Khan');
@keys = keys %data;
$size = @keys;
print "c - Hash size: $size\n";

6. Declaração condicional em Perl: if… elsif… else

#!/usr/local/bin/perl
$num = 50;
# check condition using if statement
if( $num == 40 ) (
# print the following if true
printf "num has a value which is 20\n";
) elsif( $num == 60 ) (
# else print if the next condition is true
printf "num has a value which is 30\n";
) else (
# if none is true print following
printf "num has a value which is $num\n";
)

7. Declaração condicional em Perl: a menos que… elsif… else

#!/usr/local/bin/perl,
$num = 50;
# check condition using unless statement
unless( $num == 25) (
# if condition is false then print the following
printf "num has a value which is not 25\n";
) elsif( $num == 55) (
# if condition is true then print the following
printf "num has a value which is 55";
) else (
# if both the condition is dissatisfied, print the
original value
printf "num has a value which is $num\n";
)

8. Loops em Perl: While loop

#!/usr/local/bin/perl
$i = 1;
# while loop
while( $i < 5 ) (
printf "Value of i: $i\n";
$i = $i + 1;
)

9. Loops em Perl: Até o Loop e For Loop

#!/usr/local/bin/perl
$i = 1;
# until loop
until( $i > 5 ) (
printf "Value of i: $i\n";
$i = $i + 1;
)
# for loop
for ($j = 0; $j < 3; $j++) (
printf "Value of j: $j\n";
)

10. Loops em Perl: do… while Loop

#!/usr/local/bin/perl
$i = 10;
# do…while loop
do(
printf "Value of i: $i\n";
$i = $i + 1;
)
while( $i < 20 );

Comandos Perl avançados

1. Programação de soquetes em Perl: Server

#!/usr/bin/perl -w
# Filename : server.pl
use strict;
use Socket;
# use port 8081 as default
my $port = shift || 8081;
my $protocol = getprotobyname('tcp');
my $server = "localhost"; # Host IP running the
server
# create a socket, make it reusable
socket(SOCKET, PF_INET, SOCK_STREAM,
$protocol)
or die "Can't open socket $!\n";
setsockopt(SOCKET, SOL_SOCKET,
SO_REUSEADDR, 1)
or die "Can't set socket option to SO_REUSEADDR
$!\n";
# bind to a port, then listen
bind( SOCKET, pack_sockaddr_in($port,
inet_aton($server)))
or die "Can't bind to port $port! \n";
listen(SOCKET, 5) or die "listen: $!";
print "SERVER started on port $port\n";
# accepting a connection
my $client_addr;
while ($client_addr = accept(NEW_SOCKET,
SOCKET)) (
# send them a message, close connection
my $name = gethostbyaddr($client_addr,
AF_INET );
print NEW_SOCKET "Smile from the server";
print "Connection recieved from $name\n";
close NEW_SOCKET;
)

2. Programação de soquetes em Perl: Client

!/usr/bin/perl -w
# Filename : client.pl
use strict;
use Socket;
# initialize host and port
my $host = shift || 'localhost';
my $port = shift || 8081;
my $server = "localhost"; # Host IP running the
server
# create the socket, connect to the port
socket(SOCKET, PF_INET, SOCK_STREAM, (getproto
byname('tcp'))(2))
or die "Can't create a socket $!\n";
connect( SOCKET, pack_sockaddr_in($port,
inet_aton($server)))
or die "Can't connect to port $port! \n";
my $line;
while ($line = ) (
print "$line\n";
)close SOCKET or die "close: $!";

3. Conectividade do banco de dados usando Perl

#!/usr/bin/per
use DBI
use strict;
my $driver = "mysql";
my $database = "DBTEST";
my $dsn = "DBI:$driver:database=$database";
my $userid = "user123";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password
) or die $DBI::errstr;

4. Programação CGI usando Perl

#!/usr/bin/perl
print "Content-type:text/html\r\n\r\n";
print '';
print '';
print 'Hello Perl - CGI Example';
print '';
print '';
print '

Olá Perl! Este é um exemplo de programa CGI

';
impressão '';
impressão '';
1;

Dicas e truques para usar comandos Perl

Diz-se que Perl é uma mistura de todas as linguagens, isto é, vem equipado com os melhores recursos das principais linguagens de programação. O aspecto mais importante é dominar o básico e prosseguir com a prática desse idioma. Atualização e auto-aperfeiçoamento é a chave para o sucesso.

Conclusão

Os programas acima são exemplos que ajudarão uma entidade a entender o básico e prosseguir com o aprimoramento automático. Isso foi dito como uma linguagem de programação feia, mas, na verdade, apresenta uma ampla variedade de recursos. Recomenda-se seguir este documento para compilar códigos e entender o que está acontecendo no próprio programa.

Artigos recomendados

Este foi um guia para os comandos Perl. Aqui discutimos comandos Perl básicos, imediatos e avançados. Você também pode consultar o seguinte artigo para saber mais:

  1. Usos dos comandos do Tableau
  2. Como usar os comandos do HBase
  3. Comandos do MongoDB
  4. Importância dos Comandos Pig
  5. Programação de soquete em Python