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.
# To get all the properties of an object you can use the module Data::Dumper, included with core perl:
# use Data::Dumper;
# print Dumper($object);
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;
всякое
CONTEXTS SIGILS ref ARRAYS HASHES
void $scalar SCALAR @array %hash
scalar @array ARRAY @array[0, 2] @hash{'a', 'b'}
list %hash HASH $array[0] $hash{'a'}
&sub CODE
*glob GLOB SCALAR VALUES
FORMAT number, string, ref, glob, undef
REFERENCES
\ reference $$foo[1] aka $foo->[1]
$@%&* dereference $$foo{bar} aka $foo->{bar}
[] anon. arrayref ${$$foo[1]}[2] aka $foo->[1]->[2]
{} anon. hashref ${$$foo[1]}[2] aka $foo->[1][2]
\() list of refs
SYNTAX
OPERATOR PRECEDENCE foreach (LIST) { } for (a;b;c) { }
-> while (e) { } until (e) { }
++ -- if (e) { } elsif (e) { } else { }
** unless (e) { } elsif (e) { } else { }
! ~ \ u+ u- given (e) { when (e) {} default {} }
=~ !~
* / % x NUMBERS vs STRINGS FALSE vs TRUE
+ - . = = undef, "", 0, "0"
<< >> + . anything else
named uops == != eq ne
< > <= >= lt gt le ge < > <= >= lt gt le ge
== != <=> eq ne cmp ~~ <=> cmp
&
| ^ REGEX MODIFIERS REGEX METACHARS
&& /i case insensitive ^ string begin
|| // /m line based ^$ $ str end (bfr \n)
.. ... /s . includes \n + one or more
?: /x ignore wh.space * zero or more
= += last goto /p preserve ? zero or one
, => /a ASCII /aa safe {3,7} repeat in range
list ops /l locale /d dual | alternation
not /u Unicode [] character class
and /e evaluate /ee rpts \b word boundary
or xor /g global \z string end
/o compile pat once () capture
DEBUG (?:p) no capture
-MO=Deparse REGEX CHARCLASSES (?#t) comment
-MO=Terse . [^\n] (?=p) ZW pos ahead
-D## \s whitespace (?!p) ZW neg ahead
-d:Trace \w word chars (?<=p) ZW pos behind \K
\d digits (?<!p) ZW neg behind
CONFIGURATION \pP named property (?>p) no backtrack
perl -V:ivsize \h horiz.wh.space (?|p|p)branch reset
\R linebreak (?<n>p)named capture
\S \W \D \H negate \g{n} ref to named cap
\K keep left part
FUNCTION RETURN LISTS
stat localtime caller SPECIAL VARIABLES
0 dev 0 second 0 package $_ default variable
1 ino 1 minute 1 filename $0 program name
2 mode 2 hour 2 line $/ input separator
3 nlink 3 day 3 subroutine $\ output separator
4 uid 4 month-1 4 hasargs $| autoflush
5 gid 5 year-1900 5 wantarray $! sys/libcall error
6 rdev 6 weekday 6 evaltext $@ eval error
7 size 7 yearday 7 is_require $$ process ID
8 atime 8 is_dst 8 hints $. line number
9 mtime 9 bitmask @ARGV command line args
10 ctime 10 hinthash @INC include paths
11 blksz 3..10 only @_ subroutine args
12 blcks with EXPR %ENV environment
# Чтобы избавиться в выводе от сообщений "Wide character in print at":
use open qw( :std :encoding(UTF-8) );
Часто используемые модули
Для некоторых модулей необходимо настроить локали.
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