====== Язык программирования Perl ======
===== Установка модулей =====
==== С использованием CPAN ====
[[http://search.cpan.org/]]
[root@lb2 ~]# perl -MCPAN -e shell
cpan[1]> install Encode::IMAPUTF7
===== Примеры программ =====
==== Пример 1 ====
* Отключение буферизации вывода
* Чтение данных с STDIN
* Регулярный разбор полей строки
# cat readstdin.pl
#!/usr/bin/perl
$|=1;
while(<>) {
print $_;
if (/^(allow|deny) ([^ ]+) ([^ ]+) ([^ ]+) (.*$)/) {
$act=$1;
$proto=$2;
$src=$3;$dst=$4;$port=$5;
$count++;
print "ipfw -q add $act $proto from $src to $dst $port\n";
}
}
==== Пример 2 ====
* Усиление контроля синтаксиса
* Обработка аргументов
* Использование внешних утилит
* Регулярный разбор полей строковой переменной
# cat show_cdp_neighbors.pl
#!/usr/bin/perl
use strict;
use warnings;
my ($ip) = @ARGV;
unless($ip) {
die "Need ip\n";
}
my $sw=`snmpget -On -m ALL -c public -v2c $ip sysName.0 2>/dev/null`;
print "neibors for switch: $sw\n";
foreach my $i (`snmpwalk -On -v2c -c public -m ALL $ip .1.3.6.1.4.1.9.9.23.1.2.1.1.6 2>/dev/null`) {
$i=~/.*STRING: (.*)/;
print "$1\n";
}
==== Пример 3 ====
* Использование MySQL
* autoincrement
* transaction
* error handling
CREATE TABLE
table1 (
a INT NOT NULL AUTO_INCREMENT,
b INT NOT NULL,
PRIMARY KEY(a)
);
CREATE TABLE
table2 (
b INT NOT NULL,
a INT NOT NULL,
PRIMARY KEY(b)
);
CREATE TABLE
table3 (
b INT NOT NULL,
a INT NOT NULL
);
# cat example3.pl
#!/usr/bin/perl
use DBI;
print "Start\n";
my $dsn = 'DBI:mysql:test:127.0.0.1:3306';
my $db_user_name = 'test';
my $db_password = 'test';
printf "Connect to test\n";
my %attr = (AutoCommit=>0,RaiseError=>1,HandleError => \&DBerror);
my $dbh = DBI->connect($dsn, $db_user_name, $db_password, \%attr);
my $sth = $dbh->prepare(qq{SET NAMES 'utf8'});
$sth->execute() or print "Cannot execute: " . $sth->errstr();
printf "Loop\n";
MAINLOOP:
for (my $c = 10; $c >= 1; $c--) {
my $b = int(rand(10));
$sth = $dbh->prepare(qq{insert into table1 (b) values ($b)});
#print $sth->{Statement};
$sth->execute() or next MAINLOOP;
$sth = $dbh->prepare(qq{select LAST_INSERT_ID()});
$sth->execute() or next MAINLOOP;
my ($a)=$sth->fetchrow_array();
print "a = $a; b = $b\n";
$sth = $dbh->prepare(qq{insert into table2 (b, a) values ($b, $a)});
$sth->execute() or next MAINLOOP;
$sth = $dbh->prepare(qq{insert into table3 (a, b) values ($a, $b)});
$sth->execute() or next MAINLOOP;
$dbh->commit() or next;
}
$sth->finish();
$dbh->disconnect();
exit 0;
sub DBerror(){
my $err = shift;
print "ROLLBACK $err\n";
$dbh->rollback();
}
==== Пример 4 ====
* Использование UTF8
* Работа с XML форматом ([[https://stackoverflow.com/questions/46167194/get-value-of-elements-using-xmldom|Get value of elements using XML::DOM]])
=== Исходный файл ===
# cat postgraduate.xml
=== Текст программы ===
# cat xml2txt.pl
#!/usr/bin/perl -w
use XML::DOM;
use strict;
use utf8;
binmode(STDOUT,':utf8');
my $parser = new XML::DOM::Parser;
my $doc = $parser->parsefile ('postgraduate.xml');
my @nodes =$doc->getElementsByTagName("postgraduate");
foreach my $node (@nodes) {
# print $node->toString;
my $uuid = $node->getAttributeNode ("uuid")->getValue;
my $lastname = $node->getAttributeNode ("lastname")->getValue;
my $firstname = $node->getAttributeNode ("firstname")->getValue;
my $middlename = $node->getAttributeNode ("middlename")->getValue;
print "$uuid,$lastname,$firstname,$middlename\n";
}
==== Пример 5 ====
* [[http://www.communigate.ru/CGPerl/|CommuniGate Pro Perl Interface]]
* [[https://www.communigate.ru/main/purchase/scriptrepository.html|Библиотека скриптов для CommuniGate Pro (бесплатно)]]
# wget https://www.communigate.ru/CGPerl/CLI.pm
# mv CLI.pm /etc/perl/
# cat addcgpuser.pl
#!/usr/bin/perl
use strict;
use CLI;
my ($AccountName,$RealName,$Password) = @ARGV;
my $cli = new CGP::CLI( { PeerAddr => '127.0.0.1',
PeerPort => 106,
login => 'postmaster',
password => 'Pa$$w0rd'
} )
|| die "Can't login to CGPro: ".$CGP::ERR_STRING."\n";
my $UserData;
@$UserData{'RealName'}=$RealName;
@$UserData{'Password'}=$Password;
$cli->CreateAccount(accountName => $AccountName,
settings => $UserData)
|| die "Can't create account: ".$CGP::ERR_STRING."\n";
$cli->Logout;
exit;
mail# ./addcgpuser.pl user3 'Сидор Сидорович Сидоров' password3
==== Пример 6 ====
* Perl CGI
* http://....hello.pl?name=ivanov
$ cat hello.pl
#!/usr/bin/perl
use strict;
use CGI;
my $q=new CGI();
my $name=$q->param('name');
print qq|
Hello $name
|;
==== Ссылки ====
* [[http://codecry.com/perl/random-password-generator|Random Password Generator in Perl]]
* [[http://www.xgu.ru/wiki/%D0%A2%D1%80%D0%B0%D0%BD%D1%81%D0%BB%D0%B8%D1%82|Транслит]]