CPAN
Апгрейд CPAN и всех установленных модулей до самой свежей версии:
sudo perl -MCPAN -e 'upgrade'
Насильная установка модуля в CPAN минуя тесты:
force install clean <MODULE>::<submodule>
Mojolicious
<% Строчный Perl %>
<%= Выражение Perl, заменяемое результатом с XML экранированием %>
<%== Выражение Perl, заменяемое результатом без какой-либо обработки %>
<%# Комментарий, полезно для отладки %>
% Строка Perl
%= Строка выражения Perl, заменяемое результатом с XML экранированием
%== Строка выражения Perl, заменяемое результатом без какой-либо обработки, НЕБЕЗОПАСНО при значениях принятых с клиента
%# Строка комментария, полезно для отладки
Посмотреть header страницы, используя curl:
curl -I http://localhost:48666/
ООП в Perl
# Perl OOP rules
# There are three important rules in Perl object oriented programming:
# - A class is a package.
# - An object is a reference that knows its class.
# - A method is a subroutine.
package Being;
use strict;
# which value should we return in case of not defined value
my $nothing = 'VOID';
# In Perl, we use a subroutine or method named new() to construct the object. The subroutine name is not mandatory so you can use any subroutine name you want, but be consistent.
# Whenever you call the summon() method, Perl automatically passes the class name Being as the first argument to the special array @_.
sub summon {
my ($class,$args) = @_;
# The built-in function bless is used to bless the reference to the class and return an instance of the class.
# The following illustrates the syntax of the bless() function:
# object = bless reference, classname;
#my $self = bless {align => $args->{align},
# name => $args->{name},
# age => $args->{age},
# # set start to the current time
# start => time
# }, $class;
my $self = {start => time};
$self->{name} = $args->{name} if defined $args->{name};
$self->{align} = $args->{align} if defined $args->{align};
$self->{age} = $args->{age} if defined $args->{age};
bless $self, $class;
return $self;
}
# get name of the being
sub get_name {
my $self = shift;
return defined($self->{name}) ? $self->{name} : $nothing;
}
# set new name for the being
sub set_name {
my ($self,$new_name) = @_;
$self->{name} = $new_name if defined($new_name);
return $self->{name};
}
# get age of the being
sub get_age {
my $self = shift;
return defined($self->{age}) ? $self->{age} : $nothing;
}
# set age for the being
sub set_age {
my ($self,$new_age) = @_;
$self->{age} = $new_age if defined($new_age);
return $self->{age};
}
# get align
sub get_align {
my $self = shift;
return defined($self->{align}) ? $self->{align} : $nothing;
}
# set align
sub set_align {
my ($self,$new_align) = @_;
$self->{align} = $new_align if defined($new_align);
return $self->{align};
}
# return all properties of object especially formatted
sub to_string {
my $self = shift;
my $result;
print "-"x15,"\n";
foreach my $s (keys %$self) {
$self->{$s} = $nothing unless defined $self->{$s};
$result .= "$s: $self->{$s}\n";
}
return $result;
}
# If invoked with arguments, then interpret them as key+value pairs
# already existed key will be overwritten
sub add {
my $self = shift;
if (@_) {
my %extra = @_;
@$self{keys %extra} = values %extra;
}
}
# clear properties of object
sub purify {
my $self = shift;
foreach my $s (keys %$self) {
print "Destroying the \"$s\" property in the name of Free Memory!\n";
delete $self->{$s};
}
}
# Create a method named DESTROY.
# This will be invoked when there are no more references to the object, or else when the program shuts down, whichever comes first.
# You don't need to do any memory deallocation here, just any finalization code that makes sense for the class.
sub DESTROY{
my $self = shift;
printf("$self dying at %s\n", scalar localtime);
}
1;
-------------------------------------------------------------------------------------------------------------------------
package BeingChild;
# родительский класс
use base Being;
use warnings;
use strict;
# переопределяем конструктор
sub new {
my($class) = @_;
my $self = Being::new($class);
$self->{name} = 'Diz iz BeingChild';
return $self;
}
# тут можно объявить дополнительные методы
1;
-------------------------------------------------------------------------------------------------------------------------
use strict;
use warnings;
# use our Being class
use Being;
# We called the method summon() of the Being class and get an object $mammoth.
# We passed a hash reference to the summon() method containing align, name and age.
my $mammoth = Being->summon({
align =>'Chaotic Neutral',
name => 'Mammoth',
age => 30000});
# We called the method summon() of the Being class and get an object $quetza.
# We passed a hash reference to the summon() method containing name, align and age.
my $quetza = Being->summon({ name => 'Quetzalcoatle',
align =>'Chaotic Neutral',
age => 15231});
# Another possible syntax-way to call method summon() of the Being class and get an object $something with no arguments.
my $something = summon Being();
# We called the method add() of the Being class to add some properties to $something object
$something->add(leg2 => 'right', arm2 => 'left', name => 'sometheng');
# print properties by using corresponding method
print $mammoth->to_string();
print $quetza->to_string();
print $something->to_string();
# print property
print $something->{name};
# We called the method purify() of the Being class to clean object's properties
$something->purify();
DBI connection strings
MySQL:
use DBI;
my $dbh = DBI->connect('DBI:mysql:database=information_schema;host=localhost;port=3306','root','rootpassword',{AutoCommit=>0,RaiseError=>1,PrintError=>1}) or die $DBI::errstr;
MSSQL windows login:
use DBI;
my $dbh = DBI->connect('DBI:ODBC:Driver={SQL Server};Server=11.11.111.111;UID=DOMAINNAME/LOGIN;PWD=PASSWORD') or die $DBI::errstr;
MSSQL windows authentication:
use DBI;
my $dbh = DBI->connect('DBI:ADO:Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=IP;Initial Catalog=DBNAME') or die $DBI::errstr;
Часто используемые модули
Для некоторых модулей необходимо настроить локали.
sudo locale-gen en_US
sudo locale-gen en_US.UTF-8
sudo locale-gen ru_RU.UTF-8
sudo dpkg-reconfigure locales
Обновляем модули для Perl'а из консоли CPAN (sudo нужно для доступа к записи файлов), заодно апгрейдим сам CPAN (может занять до 20 минут):
sudo cpan
upgrade
install YAML
install Mojolicious
#для нижеследующей строки требуется установить пакет: sudo apt-get install build-essential
install LWP::Simple
install Mail::IMAPClient
# для нижеследующей строки требуется force install Mojolicious::Plugin::ParamExpand
force install Mojolicious::Plugin::FormFields
# для нижеследующего требуется sudo apt-get install mongodb<
install MongoDB
# для нижеследующего требуется sudo apt-get install postgresql libdbd-mysql-perl libdbi-perl libdbd-pg-perl libpq-dev python-dev libmysql++-dev
# а также в CPAN'е: install Class::HPLOO
install DBD
install DBI
install DBD::SQLite
Math::GMP
Math::Random::Secure
# для нижеследующего требуется sudo apt-get install libgmp-dev openssl
Net::SSH::Perl