Introduzione ai comandi Perl

Perl è un linguaggio di programmazione. Progettato in precedenza solo per l'editing di testo, è ora utilizzato per molti scopi come l'amministrazione del sistema in Linux, lo sviluppo web, la programmazione di rete, ecc. L'architetto capo e creatore di Perl sono Larry Wall. È stato creato nel 1987 ed è ancora usato come un importante linguaggio di programmazione. Perl è un linguaggio di alto livello. È anche un linguaggio di programmazione interpretato e dinamico. Ora impareremo in dettaglio i comandi Perl.

Comandi di base Perl

1. Comando Perl di base per stampare in Perl

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

2. Commento a riga singola in Perl

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

3. Commento a più righe in 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. Assegnazione delle variabili in Perl (interpolazione di variabili tra virgolette doppie)

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

5. Fuga dal personaggio in Perl

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

6. In Perl, le stringhe hanno un comportamento diverso con virgolette doppie e virgolette singole. Mentre le virgolette doppie consentono l'interpolazione, le virgolette singole no.

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

7. Maiuscole nel 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. Assegnazione variabile scalare in 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. Semplici operazioni scalari in 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. Letterature speciali in 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";

Comandi Perl intermedi

1. Matrici in Perl

L'indice dell'array inizia da 0. L'indice negativo indica gli elementi dell'ultima posizione. Esempio sotto.

#!/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. Matrici per elementi in una sequenza

#!/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. Aggiunta e rimozione di elementi array

#!/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. Hash in Perl

L'hash è un concetto di coppia valore-chiave. Di seguito è riportato un esempio per creare un 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. Aggiunta e rimozione dell'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. Dichiarazione condizionale in 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. Dichiarazione condizionale in Perl: a meno che … 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. Loop in Perl: loop Loop

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

9. Loop in Perl: Until 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. Loop in 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 );

Comandi avanzati Perl

1. Programmazione socket in 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. Programmazione socket in 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. Connettività del database tramite 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. Programmazione CGI con Perl

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

Ciao Perl! Questo è un esempio di programma CGI

';
Stampa '';
Stampa '';
1;

Suggerimenti e trucchi per usare i comandi Perl

Si dice che Perl sia una miscela di tutti i linguaggi, cioè è dotato delle migliori caratteristiche dei principali linguaggi di programmazione. L'aspetto più importante è padroneggiare le basi e procedere con la pratica di questo linguaggio. L'aggiornamento e l'auto-miglioramento è la chiave del successo.

Conclusione

I programmi di cui sopra sono esempi che aiuteranno un'entità a comprendere le basi e procedere con l'auto-miglioramento. Questo è stato detto un brutto linguaggio di programmazione, ma in realtà mostra una vasta gamma di funzionalità. Si consiglia di seguire questo documento per compilare codici e comprendere cosa sta succedendo nel programma stesso.

Articoli consigliati

Questa è stata una guida ai comandi Perl. Qui abbiamo discusso dei comandi Perl di base, immediati e avanzati. Puoi anche leggere il seguente articolo per saperne di più-

  1. Usi dei comandi del tableau
  2. Come usare i comandi HBase
  3. Comandi MongoDB
  4. Importanza dei comandi suini
  5. Programmazione socket in Python

Categoria: