Показаны сообщения с ярлыком perl. Показать все сообщения
Показаны сообщения с ярлыком perl. Показать все сообщения

25.12.2008

each func

  while ( my ($key, $value) = each(%hash) ) {
  print "$key => $value\n";
  }

23.12.2008

sub hup

sub hup {
my $self = shift;
 
 return $self->status() if kill('HUP', $self->__pid());

01.12.2008

&while perl

perl -e '$_=1;while ($_ <= 10) { print; $_++;}'

24.11.2008

perl var

$_      область ввода или поиска по образцу, используемая по умолчанию
$. номер текущей считанной строки из текущего входного файла
$/ разделитель входных записей (обычно - символ новой строки \n)
$] номер версии Perl (например, 5.008007)
$0 имя файла текущей исполняемой Perl-программы
$@ сообщение об ошибке при выполнении в блоках eval или do
$! текущий номер ошибки или сообщение об ошибке
$^E уточненное сообщение об ошибке
$^T время начала выполнения программы (в формате функции time)

21.11.2008

mass copy perl

perl -e 'my $d=`date '+%H_%d%m%y'`;@_=`ls -1|grep log\$`; foreach $_(@_) { chomp $_; print "copy $_ to $_\.$d\n"; system ("cp -v $_ $_\.$d");} ;'

13.11.2008

perl short spam script

perl -we '@_=`find /tmp/mail -type f`;foreach $_(@_){chomp; print "spaming $_\n"; system ("cat $_|sendmail user");}'

for bash:

for i in /var/SPAM/* ; do cat $i | sendmail sed ; echo "spaming $i"; done

25.10.2008

simple mailer

#!/usr/bin/perl -w
use strict;
my $dir="/var/SPAM/";
my @mail=`ls -1 $dir`;
#print "This messages will be sent:\n@mail";
my $msg;
foreach $msg(@mail)
{
chomp $msg;
print "Spaming msg $dir$msg\n";
system ("cat $dir$msg | sendmail sed");

}

24.10.2008

Mail Builder

#!/usr/bin/perl -w
use strict;
use Mail::Builder;
my $mail = Mail::Builder->new();
$mail->from('tester@localhost.ru','tester');
$mail->to('sed@localhost.ru','sed');
$mail->subject('Test message unicode');
$mail->htmltext('

Moeeeoooowwwwww

... ');
$mail->attachment('blblabla.dpf');
print $mail->stringify;

11.10.2008

split & join

use strict;
my $glue = "A";
my @pieces = qw/B C D/;
my $result = join $glue, @pieces;
print "@pieces\n";
print "$result\n";

my $x = join ":",4,6,8,10,12;
print "$x\n";
my @values = split /:/,$x;
my $z = join "-", @values;
print "$z\n";

каша )))))

use strict;
$_ = "white pretty cat\n";
print;
if (s/(\w+) (\w+)/$2, $1/) { print "Begin changing $2 cat!!!\n";
}
s{^}{huge, };
s#,.*te##; s<\w+$>{($`!)$&};
s[\s+(!\W+)]{$1 }; s%huge%Fat%;
s[$]{asaur !!!\n}; s*^*AAAA!!! *;
print; s/(\bc.*\b)/\U$1/gi; print;

search and change

$_ = "I love my prety cat.\n";
print;
print "But when i lose my job.\n";
s/love/eat/;
print;

Выод:
I love my pretty cat.
But when i lose my job.
I eat my prety cat.

автоматически создаваемые переменные сравнения

use strict;
if ("Hello there, dody" =~ /\s(\w+),/) {
print "matched word - '$&'.\n";
print "all words was - ($`)($&)($').\n";
}

предшествующая строка $` само совпадение $& и следующая строка $'
Вывод:
matched word - ' there,'.
all words was - (Hello)( there,)( dody).

Эти переменные немного тормозят обработку остальных регулярок, поэтому если нужно использовать только $& можно просто заключить всю регулярку в скобки и воспользоваться ссылкой примерно так:
if ("Hello there, dody" =~ /(\s(\w+),)/) {
print "matched word - '$1'.\n";
}

Соханение специальных переменных в памяти

#!/usr/bin/perl -w
use strict;
$_ = "Hello there, neightbor";
if (/(\w+) (\w+), (\w+)/) {
print "The first words was \"$1\" \"$2\" \"$3\".\n";
}
my $first_word = $1;
#don't forget to save $1 if you nedd it
$_ = "Go here dody";
if (/(\w+) (\w+) (\w+)/) {
print "The second words was \"$1\" \"$2\" \"$3\".\n";
}
print "The last word of last words was \"$3\".\n";
print "The first word of first words was \"$first_word\".\n";

perl regexp check

perl -e 'while (<>) { if (/192/) { print; }}' /etc/hosts

perl grep

#!/usr/bin/perl -w
use strict;
print "Enter regexp: ";
chomp (my $S = );
while (<>) {
if (/$S/) {
print;
}
}

Чтобы "подсветить найденное выражение можно изменить вот так

#!/usr/bin/perl -w
use strict;
print "Enter regexp: ";
chomp (my $S =
);
while (<>) {
if (/$S/) {
chomp;
print "$`<$&>$'\n";
}
}

табличка

use strict;
print "enter widht taht you want\n";
chomp(my $widht = );

print "Enter some lines, and press Cntrl+D\n";
chomp(my @lines = );

print "-" x $widht,"|\n";#control line for debug
my $format = "%${widht}s|\n" x @lines;
printf $format, @lines;

Аналоги команд на перле

print <>; = cat
print sort <>; = sort
print reverse <>; = tac

Массивы и функция printf

use strict;
my @items = qw( Wilma mario dino pebbles );
my $format = "The items are:\n" . ("%10s\n" x @items);
#print "The format is <<$format>>\n"; # for debug
printf $format, @items;

Вывод:
The items are:
Wilma
mario
dino
pebbles

perl subs

sub cat { while (defined($line = <>)) {
chomp($line);
print "$line\n";
}
}