(?1)
)
/x;
use feature ":5.10";
my $re = qr
/^
(
\(
(?:
[^()]
|
(?1)
)*
\)
)
$/x;
my @tests = (
"()",
"(",
"(1+2)",
"1+2)",
"(1-(2+3))",
"(1-(2+3)",
"(1+2+3*(4-5)+6/(2+3-(4*5*(6-7)))-8)",
);
for (@tests) {
say /$re/ ? "ok" : "not ok", " $_";
}
/^(\((?:[^()]|(?1))*\))$/
-----------------------------------------------------------------------------------------------------------------
Работаем с OpenDocument из Perl
Валентин Синицын
perl Makefile.pl
make
make test
make install
ppm install OpenOffice-OODoc
$doc->outputDelimitersOff();
my $content = $doc->getTextContent();
$content =~ s/\s+//mg;
print length $content;
use Term::ANSIColor qw(:constants);
...
my $doc = ooDocument(file => $file, member => 'content');
$doc->{'delimiters'}{'text:h'} = { 'begin' => RED, 'end' => RESET };
$doc->{'delimiters'}{'text:a'} = { 'begin' => BLUE, 'end' => RESET };
$doc->{'delimiters'}{'text:list-item'} = { 'begin' => YELLOW . '* ' . RESET, 'end' => '' };
$doc->{'delimiters'}{'text:span'} = { 'begin' => BOLD, 'end' => RESET };
$doc->outputDelimitersOn();
print scalar $doc->getTextContent();
my $doc = ooDocument(file => $i_file, member => 'content');
my $meta = ooMeta(file => $i_file);
$doc->outputDelimitersOff();
open(O_FILE, '>' . $o_file) || die "Unable to open $o_file";
my $title = $meta->title();
my $author = $meta->creator();
my $charset = ooLocalEncoding();
print O_FILE <<"__HEADER__";
$title
__HEADER__
for my $elt ($doc->selectElementsByContent('.*')) {
if ($elt->isHeading) {
print O_FILE heading($elt), "\n";
}
elsif ($elt->isParagraph) {
print O_FILE '', paragraph_content($elt), "
\n";
}
elsif ($elt->isItemList) {
print O_FILE list($elt, 1), "\n";
}
}
print O_FILE <<'__FOOTER__';
__FOOTER__
close(O_FILE);
for my $elt ($doc->selectElementsByContent('.*')) { ... }
sub heading {
my $elt = shift;
my $level = $doc->getOutlineLevel($elt);
return "" . paragraph_content($elt) . "\n";
}
sub paragraph_content {
my $para = shift;
my $result;
for my $child ($para->getChildNodes) {
if ($child->isSpan) {
$result .= span($child);
}
elsif ($child->isHyperlink) {
$result .= hyperlink($child);
}
elsif ($child->isImage) {
$result .= image($child);
}
elsif ($child->getName eq '#PCDATA') {
my $text = ooDecodeText($child->text);
$text =~ s/&/&/g;
$text =~ s/</g;
$text =~ s/>/>/g;
$result .= $text;
}
else {
warn "Element '" . $child->getName . "' was ignored\n";
}
}
return $result;
}
sub span {
my $elt = shift;
my %attrs = $doc->getStyleAttributes($doc->textStyle($elt));
if ($attrs{'properties'}->{'fo:font-weight'} eq 'bold') {
return "" . paragraph_content($elt) . "";
} elsif ($attrs{'properties'}->{'fo:font-style'} eq 'italic') {
return "" . paragraph_content($elt) . "";
}
}
1: my $is_ordered = 0;
2: my $style = $doc->getStyleElement($doc->textStyle($elt), namespace => 'text', type => 'list-style');
3: my $st = $doc->getNodeByXPath("//*[\@text:level=\"$level\"]", $style);
4: if ($st && $st->getName eq 'text:list-level-style-number') {
5: $is_ordered = 1;
6: } elsif ($st && $st->getName eq 'text:list-level-style-bullet') {
7: $is_ordered = 0;
8: } else {
9: warn 'Unknown type of the list: '. $st . "\n";
10: }
my $doc = ooDocument(file => $i_file, member => 'content');
$doc->userFieldValue('someField', 'someValue');
$doc->save($o_file);
my $block_no = 1;
my $image_no = 1;
my $anchor;
for my $para ($doc->selectParagraphsByStyle('EmbeddedPerl')) {
my $code = $doc->getText($para);
$anchor = $para;
my $result = eval $code;
die "Error in template block $block_no: $@" if ($@);
if (ref $result && $result->isElementNode) {
$doc->replaceElement($para, $result);
} else {
if ($result) {
my $new_para = $doc->insertParagraph($para);
$doc->setText($new_para, $result);
}
$doc->removeElement($para);
}
$block_no++;
}
$doc->save($o_file);
sub image {
my ($file, $width, $height) = @_;
$anchor = $doc->insertParagraph($anchor, position => 'after');
$doc->insertImageElement("Image" . $image_no++, attachment => $anchor, import => $file, size => "${width}cm, ${height}cm");
return undef;
}
-----------------------------------------------------------------------------------------------------------------
Основные процедуры для работы с деревьями
Александр Ямпольский
public struct ObjectN // объект (узел дерева)
{
public string J_NAME; // имя объекта
public long J_TYPE; // тип объекта(носитель знаний)
public long IDF, // указатель на «отца»
IDB, // указатель на «брата»
ID1C; // указатель на первого потомка
}
public static ObjectN[] obj = new ObjectN[];
FreeCell = getfreecell();
obj[FreeCell].IDF = FatherIdentifier;
obj[FreeCell].IDB = obj[FatherIdentifier].ID1C;
obj[FatherIdentifier].ID1C=FreeCell;
public static int descent(long SourceObj,int TravDepth)
// SourceObj - указатель исходного узла обхода
// TravDepth - лимит глубины обхода
{
long[] Router = new long[TravDepth]; // маршрутизатор
int Lev, // счетчик уровней дерева
cur; // вспомогательный указатель уровня
bool EOTree, // признак завершения дерева
EOLev; // признак завершения уровня
long ObjPnt, // вспомогательный указатель объекта
FirstCh; // указатель на первого потомка исходного узла
FirstCh=obj[SourceObj].ID1C;
EOTree=false;
Lev=0;
while (!EOTree && Lev0)
{
Console.WriteLine("object: {0}",obj[ObjPnt].J_NAME);
// здесь может быть процедура обработки объекта
EOTree=EOTree && (obj[ObjPnt].ID1C<1);
ObjPnt=obj[ObjPnt].IDB;
}
// подняться по массиву Router до первого ненулевого указателя на объект
cur=cur-1;
while (cur>0)
{
ObjPnt=obj[Router[cur]].IDB;
if (ObjPnt>0) break;
cur=cur-1;
}
if (cur == 0) EOLev=true;
} // обход фрагмента дерева глубиной Lev
} // цикл по уровням
return(0);
}
// фрагмент кода, реализующий отсечение
// compatible – функция, определяющая совместимость объектов
// target_j_type - тип целевого объекта
if (!compatible(obj[ObjPnt].J_TYPE, target_j_type))
{
ObjPnt=0;
break; // как если бы узел не имел потомков
}
while (ObjPnt != RootPnt)
{
// if (информация получена) break;
ObjPnt=obj[ObjPnt].IDF;
}
-----------------------------------------------------------------------------------------------------------------
Пространства имен в PHP
Александр Майоров
namespace name
{
//Здесь ваш код…
}
namespace MyNameSpace
{
int variable_1;
int variable_2;
class MyClass { ... };
}
MyNameSpace::variable1 = 10;
MyNameSpace::MyClass myObject;
using namespace name;
using name::spacemember
'value1',
'to'=>' value1',
'sort'=>' value1',
);
$str = mylib::arrays::sort::sort( $arr );
?>
'value1',
'to'=>' value2',
'sort'=>' value3',
);
$str = mylib::arrays::sort ( $arr );
?>
'value1',
'to'=>' value2',
'sort'=>' value3',
);
$str = arr::sort ( $arr );
?>
case = mylib::TString::LOWERCASE;
...
?>
function space_0( $name )
{
function foo( $argv )
{
var_dump( $argv );
}
function bar( $a1, $a2, $a3 )
{
var_dump($a1, $a2, $a3);
}
$argv = func_get_args();
unset($argv[0]);
return call_user_func_array ( $name, $argv );
}
function space_1( $name )
{
function foo( $argv )
{
var_dump( $argv );
}
function bar( $a1, $a2, $a3 )
{
var_dump($a1, $a2, $a3);
}
$argv = func_get_args();
unset($argv[0]);
return call_user_func_array ( $name, $argv );
}
var_dump( space_0('bar', 1,2,3), space_1('bar', 1,2,3) );
?>
-----------------------------------------------------------------------------------------------------------------