Aion-Fs

 view release on metacpan or  search on metacpan

README.md  view on Meta::CPAN


[map cat, grep -f, find ["hello/big", "hello/small"]];  # --> [qw/ hellow! noenter /]

my @noreplaced = replace { s/h/$a $b H/ }
    find "hello", "-f", "*.txt", qr/\.txt$/, sub { /\.txt$/ },
        noenter "*small*",
            errorenter { warn "find $_: $!" };

\@noreplaced; # --> ["hello/moon.txt"]

cat "hello/world.txt";       # => hello/world.txt :utf8 Hi!
cat "hello/moon.txt";        # => noreplace
cat "hello/big/world.txt";   # => hello/big/world.txt :utf8 Hellow!
cat "hello/small/world.txt"; # => noenter

[find "hello", "*.txt"]; # --> [qw!  hello/moon.txt  hello/world.txt  hello/big/world.txt  hello/small/world.txt  !]

my @dirs;

my $iter = find "hello", "-d";

while(<$iter>) {
    push @dirs, $_;

README.md  view on Meta::CPAN

# SUBROUTINES/METHODS

## cat ($file)

Считывает файл. Если параметр не указан, использует `$_`.

```perl
cat "/etc/passwd"  # ~> root
```

`cat` читает со слоем `:utf8`. Но можно указать другой слой следующим образом:

```perl
lay "unicode.txt", "↯";
length cat "unicode.txt"            # -> 1
length cat["unicode.txt", ":raw"]   # -> 3
```

`cat` вызывает исключение в случае ошибки операции ввода-вывода:

```perl

README.md  view on Meta::CPAN

* [File::Util](https://metacpan.org/pod/File::Util) – `File::Util->new->load_file(file => 'file.txt')`.
* [IO::All](https://metacpan.org/pod/IO::All) – `io('file.txt') > $contents`.
* [IO::Util](https://metacpan.org/pod/IO::Util) – `$contents = ${ slurp 'file.txt' }`.
* [Mojo::File](https://metacpan.org/pod/Mojo::File) – `path($file)->slurp`.

## lay ($file?, $content)

Записывает `$content` в `$file`.

* Если указан один параметр, использует `$_` вместо `$file`.
* `lay`, использует слой `:utf8`. Для указания иного слоя используется массив из двух элементов в параметре `$file`:

```perl
lay "unicode.txt", "↯"  # => unicode.txt
lay ["unicode.txt", ":raw"], "↯"  # => unicode.txt

eval { lay "/", "↯" }; $@ # ~> lay /: Is a directory
```

### See also

README.md  view on Meta::CPAN

$count # -> 3
```

### See also

* [AudioFile::Find](https://metacpan.org/pod/AudioFile::Find) – ищет аудиофайлы в указанной директории. Позволяет фильтровать их по атрибутам: названию, артисту, жа...
* [Directory::Iterator](https://metacpan.org/pod/Directory::Iterator) – `$it = Directory::Iterator->new($dir, %opts); push @paths, $_ while <$it>`.
* [IO::All](https://metacpan.org/pod/IO::All) – `@paths = map { "$_" } grep { -f $_ && $_->size > 10*1024 } io(".")->all(0)`.
* [IO::All::Rule](https://metacpan.org/pod/IO::All::Rule) – `$next = IO::All::Rule->new->file->size(">10k")->iter($dir1, $dir2); push @paths, "$f" while $f = $next->()`.
* [File::Find](https://metacpan.org/pod/File::Find) – `find( sub { push @paths, $File::Find::name if /\.png/ }, $dir )`.
* [File::Find::utf8](https://metacpan.org/pod/File::Find::utf8) – как [File::Find](https://metacpan.org/pod/File::Find), только пути файлов в _utf8_.
* [File::Find::Age](https://metacpan.org/pod/File::Find::Age) – сортирует файлы по времени модификации (наследует [File::Find::Rule](https://metacpan.org/pod/File::Find::Rule)): `File::Find::Age->in($dir1,...
* [File::Find::Declare](https://metacpan.org/pod/File::Find::Declare) – `@paths = File::Find::Declare->new({ size => '>10K', perms => 'wr-wr-wr-', modified => '<2010-01-30', recurse => 1, dirs => [$dir1] })->find`.
* [File::Find::Iterator](https://metacpan.org/pod/File::Find::Iterator) – имеет ООП интерфейс с итератором и функции `imap` и `igrep`.
* [File::Find::Match](https://metacpan.org/pod/File::Find::Match) – вызывает обработчик на каждый подошедший фильтр. Похож на `switch`.
* [File::Find::Node](https://metacpan.org/pod/File::Find::Node) – обходит иерархию файлов параллельно несколькими процессами: `tie @paths, IPC::Shareable, { key => "GLUE STRING", create => 1 }; F...
* [File::Find::Fast](https://metacpan.org/pod/File::Find::Fast) – `@paths = @{ find($dir) }`.
* [File::Find::Object](https://metacpan.org/pod/File::Find::Object) – имеет ООП интерфейс с итератором.
* [File::Find::Parallel](https://metacpan.org/pod/File::Find::Parallel) – умеет сравнивать два каталога и возвращать их объединение, пересечение и количественное перес...
* [File::Find::Random](https://metacpan.org/pod/File::Find::Random) – выбирает файл или директорию наугад из иерархии файлов.
* [File::Find::Rex](https://metacpan.org/pod/File::Find::Rex) – `@paths = File::Find::Rex->new(recursive => 1, ignore_hidden => 1)->query($dir, qr/^b/i)`.

README.md  view on Meta::CPAN


* `unlink` + `rmdir`.
* [File::Path](https://metacpan.org/pod/File::Path) – `remove_tree("dir")`.
* [File::Path::Tiny](https://metacpan.org/pod/File::Path::Tiny) – `File::Path::Tiny::rm($path)`. Не выбрасывает исключений.
* [Mojo::File](https://metacpan.org/pod/Mojo::File) – `path($file)->remove`.

## replace (&sub, @files)

Заменяет каждый файл на `$_`, если его изменяет `&sub`. Возвращает файлы, в которых не было замен.

`@files` может содержать массивы из двух элементов. Первый рассматривается как путь, а второй – как слой. Слой по умолчанию – `:utf8`.

`&sub` вызывается для каждого файла из `@files`. В неё передаются:

* `$_` – содержимое файла.
* `$a` – путь к файлу.
* `$b` – слой которым был считан файл и которым он будет записан.

В примере ниже файл "replace.ex" считывается слоем `:utf8`, а записывается слоем `:raw` в функции `replace`:

```perl
local $_ = "replace.ex";
lay "abc";
replace { $b = ":utf8"; y/a/¡/ } [$_, ":raw"];
cat  # => ¡bc
```

### See also

* [File::Edit](https://metacpan.org/pod/File::Edit) – `File::Edit->new($file)->replace('x', 'y')->save`.
* [File::Edit::Portable](https://metacpan.org/pod/File::Edit::Portable) – `File::Edit::Portable->new->splice(file => $file, line => 10, contens => ["line1", "line2"])`.
* [File::Replace](https://metacpan.org/pod/File::Replace) – `($infh,$outfh,$repl) = replace3($file); while (<$infh>) { print $outfh "X: $_" } $repl->finish`.
* [File::Replace::Inplace](https://metacpan.org/pod/File::Replace::Inplace).

## mkpath (;$path)

Как **mkdir -p**, но считает последнюю часть пути (после последней косой черты) именем файла и не создаёт её каталогом. Без параметра используе...

* Если `$path` не указан, использует `$_`.
* Если `$path` является ссылкой на массив, тогда используется путь в качестве первого элемента и права в качестве второго элемента.
* Права по умолчанию – `0755`.
* Возвращает `$path`.

README.md  view on Meta::CPAN

use lib "lib";
include("A")->new               # ~> A=HASH\(0x\w+\)
[map include, qw/A N/]          # --> [qw/A N/]
{ local $_="N"; include->ex }   # -> 123
```

## catonce (;$file)

Считывает файл в первый раз. Любая последующая попытка считать этот файл возвращает `undef`. Используется для вставки модулей js и css в резулÑ...

* `$file` может содержать массивы из двух элементов. Первый рассматривается как путь, а второй – как слой. Слой по умолчанию – `:utf8`.
* Если `$file` не указан – использует `$_`.

```perl
local $_ = "catonce.txt";
lay "result";
catonce  # -> "result"
catonce  # -> undef

eval { catonce[] }; $@ # ~> catonce not use ref path!
```

i18n/Aion/Fs.ru-en.po  view on Meta::CPAN

msgstr "The `IO::All` supermodule is not a competitor to `Aion::Fs`, because uses an OOP approach, and `Aion::Fs` is FP."

msgid "* ООП – объектно-ориентированное программирование.\n"
"* ФП – функциональное программирование."
msgstr "* OOP – object-oriented programming.\n"
"* FP – functional programming."

msgid "Считывает файл. Если параметр не указан, использует `$_`."
msgstr "Reads the file. If no parameter is specified, use `$_`."

msgid "`cat` читает со слоем `:utf8`. Но можно указать другой слой следующим образом:"
msgstr "`cat` reads with layer `:utf8`. But you can specify another layer like this:"

msgid "`cat` вызывает исключение в случае ошибки операции ввода-вывода:"
msgstr "`cat` throws an exception if the I/O operation fails:"

msgid ""
"* [autodie](https://metacpan.org/pod/autodie) – `open $f, \"r.txt\"; $s = join \"\", <$f>; close $f`.\n"
"* [File::Slurp](https://metacpan.org/pod/File::Slurp) – `read_file('file.txt')`.\n"
"* [File::Slurper](https://metacpan.org/pod/File::Slurper) – `read_text('file.txt')`, `read_binary('file.txt')`.\n"
"* [File::Util](https://metacpan.org/pod/File::Util) – `File::Util->new->load_file(file => 'file.txt')`.\n"
"* [IO::All](https://metacpan.org/pod/IO::All) – `io('file.txt') > $contents`.\n"

i18n/Aion/Fs.ru-en.po  view on Meta::CPAN

"* [File::Slurper](https://metacpan.org/pod/File::Slurper) – `read_text('file.txt')`, `read_binary('file.txt')`.\n"
"* [File::Util](https://metacpan.org/pod/File::Util) – `File::Util->new->load_file(file => 'file.txt')`.\n"
"* [IO::All](https://metacpan.org/pod/IO::All) – `io('file.txt') > $contents`.\n"
"* [IO::Util](https://metacpan.org/pod/IO::Util) - `$contents = ${ slurp 'file.txt' }`.\n"
"* [Mojo::File](https://metacpan.org/pod/Mojo::File) – `path($file)->slurp`."

msgid "Записывает `$content` в `$file`."
msgstr "Writes `$content` to `$file`."

msgid "* Если указан один параметр, использует `$_` вместо `$file`.\n"
"* `lay`, использует слой `:utf8`. Для указания иного слоя используется массив из двух элементов в параметре `$file`:"
msgstr "* If one parameter is specified, use `$_` instead of `$file`.\n"
"* `lay`, uses the `:utf8` layer. To specify a different layer, use an array of two elements in the `$file` parameter:"

msgid ""
"* [autodie](https://metacpan.org/pod/autodie) – `open $f, \">r.txt\"; print $f $contents; close $f`.\n"
"* [File::Slurp](https://metacpan.org/pod/File::Slurp) – `write_file('file.txt', $contents)`.\n"
"* [File::Slurper](https://metacpan.org/pod/File::Slurper) – `write_text('file.txt', $contents)`, `write_binary('file.txt', $contents)`.\n"
"* [IO::All](https://metacpan.org/pod/IO::All) – `io('file.txt') < $contents`.\n"
"* [IO::Util](https://metacpan.org/pod/IO::Util) – `slurp \\$contents, 'file.txt'`.\n"
"* [File::Util](https://metacpan.org/pod/File::Util) – `File::Util->new->write_file(file => 'file.txt', content => $contents, bitmask => 0644)`.\n"
"* [Mojo::File](https://metacpan.org/pod/Mojo::File) – `path($file)->spew($chars, 'UTF-8')`."
msgstr ""

i18n/Aion/Fs.ru-en.po  view on Meta::CPAN


msgid "**Внимание!** Если `errorenter` не указана, то все ошибки **игнорируются**!"
msgstr "**Attention!** If `errorenter` is not specified, then all errors are **ignored**!"

msgid ""
"* [AudioFile::Find](https://metacpan.org/pod/AudioFile::Find) – ищет аудиофайлы в указанной директории. Позволяет фильтровать их по атрибутам: названию, артисту, жÐ...
"* [Directory::Iterator](https://metacpan.org/pod/Directory::Iterator) – `$it = Directory::Iterator->new($dir, %opts); push @paths, $_ while <$it>`.\n"
"* [IO::All](https://metacpan.org/pod/IO::All) – `@paths = map { \"$_\" } grep { -f $_ && $_->size > 10*1024 } io(\".\")->all(0)`.\n"
"* [IO::All::Rule](https://metacpan.org/pod/IO::All::Rule) – `$next = IO::All::Rule->new->file->size(\">10k\")->iter($dir1, $dir2); push @paths, \"$f\" while $f = $next->()`.\n"
"* [File::Find](https://metacpan.org/pod/File::Find) – `find( sub { push @paths, $File::Find::name if /\\.png/ }, $dir )`.\n"
"* [File::Find::utf8](https://metacpan.org/pod/File::Find::utf8) – как [File::Find](https://metacpan.org/pod/File::Find), только пути файлов в _utf8_.\n"
"* [File::Find::Age](https://metacpan.org/pod/File::Find::Age) – сортирует файлы по времени модификации (наследует [File::Find::Rule](https://metacpan.org/pod/File::Find::Rule)): `File::Find::Age->in($dir1...
"* [File::Find::Declare](https://metacpan.org/pod/File::Find::Declare) – `@paths = File::Find::Declare->new({ size => '>10K', perms => 'wr-wr-wr-', modified => '<2010-01-30', recurse => 1, dirs => [$dir1] })->find`.\n"
"* [File::Find::Iterator](https://metacpan.org/pod/File::Find::Iterator) – имеет ООП интерфейс с итератором и функции `imap` и `igrep`.\n"
"* [File::Find::Match](https://metacpan.org/pod/File::Find::Match) – вызывает обработчик на каждый подошедший фильтр. Похож на `switch`.\n"
"* [File::Find::Node](https://metacpan.org/pod/File::Find::Node) – обходит иерархию файлов параллельно несколькими процессами: `tie @paths, IPC::Shareable, { key => \"GLUE STRING\", create => 1 }...
"* [File::Find::Fast](https://metacpan.org/pod/File::Find::Fast) – `@paths = @{ find($dir) }`.\n"
"* [File::Find::Object](https://metacpan.org/pod/File::Find::Object) – имеет ООП интерфейс с итератором.\n"
"* [File::Find::Parallel](https://metacpan.org/pod/File::Find::Parallel) – умеет сравнивать два каталога и возвращать их объединение, пересечение и количественное переÑ...
"* [File::Find::Random](https://metacpan.org/pod/File::Find::Random) – выбирает файл или директорию наугад из иерархии файлов.\n"
"* [File::Find::Rex](https://metacpan.org/pod/File::Find::Rex) – `@paths = File::Find::Rex->new(recursive => 1, ignore_hidden => 1)->query($dir, qr/^b/i)`.\n"

i18n/Aion/Fs.ru-en.po  view on Meta::CPAN

"* [Path::Iterator::Rule](https://metacpan.org/pod/Path::Iterator::Rule) – `$i = Path::Iterator::Rule->new->file; @paths = $i->clone->size(\">10k\")->all(@dirs); $i->size(\"<10k\")...`.\n"
"* [Path::Class::Each](https://metacpan.org/pod/Path::Class::Each) – `dir($dir)->each(sub { push @paths, \"$_\" })`.\n"
"* [Path::Class::Iterator](https://metacpan.org/pod/Path::Class::Iterator) – `$i = Path::Class::Iterator->new(root => $dir, depth => 2); until ($i->done) { push @paths, $i->next->stringify }`.\n"
"* [Path::Class::Rule](https://metacpan.org/pod/Path::Class::Rule) – `@paths = Path::Class::Rule->new->file->size(\">10k\")->all($dir)`."
msgstr ""
"* [AudioFile::Find](https://metacpan.org/pod/AudioFile::Find) – searches for audio files in the specified directory. Allows you to filter them by attributes: title, artist, genre, album and track.\n"
"* [Directory::Iterator](https://metacpan.org/pod/Directory::Iterator) – `$it = Directory::Iterator->new($dir, %opts); push @paths, $_ while <$it>`.\n"
"* [IO::All](https://metacpan.org/pod/IO::All) – `@paths = map { \"$_\" } grep { -f $_ && $_->size > 10*1024 } io(\".\")->all(0)`.\n"
"* [IO::All::Rule](https://metacpan.org/pod/IO::All::Rule) – `$next = IO::All::Rule->new->file->size(\">10k\")->iter($dir1, $dir2); push @paths, \"$f\" while $f = $next->()`.\n"
"* [File::Find](https://metacpan.org/pod/File::Find) – `find( sub { push @paths, $File::Find::name if /\\.png/ }, $dir )`.\n"
"* [File::Find::utf8](https://metacpan.org/pod/File::Find::utf8) – like [File::Find](https://metacpan.org/pod/File::Find), only file paths are in _utf8_.\n"
"* [File::Find::Age](https://metacpan.org/pod/File::Find::Age) – sorts files by modification time (inherits [File::Find::Rule](https://metacpan.org/pod/File::Find::Rule)): `File::Find::Age->in($dir1, $dir2)`.\n"
"* [File::Find::Declare](https://metacpan.org/pod/File::Find::Declare) – `@paths = File::Find::Declare->new({ size => '>10K', perms => 'wr-wr-wr-', modified => '<2010-01-30', recurse => 1, dirs => [$dir1] })->find`.\n"
"* [File::Find::Iterator](https://metacpan.org/pod/File::Find::Iterator) – has an OOP interface with an iterator and the `imap` and `igrep` functions.\n"
"* [File::Find::Match](https://metacpan.org/pod/File::Find::Match) – calls a handler for each matching filter. Similar to `switch`.\n"
"* [File::Find::Node](https://metacpan.org/pod/File::Find::Node) – traverses the file hierarchy in parallel by several processes: `tie @paths, IPC::Shareable, { key => \"GLUE STRING\", create => 1 }; File::Find::Node->new(\".\")->process(sub { my $...
"* [File::Find::Fast](https://metacpan.org/pod/File::Find::Fast) – `@paths = @{ find($dir) }`.\n"
"* [File::Find::Object](https://metacpan.org/pod/File::Find::Object) – has an OOP interface with an iterator.\n"
"* [File::Find::Parallel](https://metacpan.org/pod/File::Find::Parallel) – can compare two directories and return their union, intersection and quantitative intersection.\n"
"* [File::Find::Random](https://metacpan.org/pod/File::Find::Random) – selects a file or directory at random from the file hierarchy.\n"
"* [File::Find::Rex](https://metacpan.org/pod/File::Find::Rex) – `@paths = File::Find::Rex->new(recursive => 1, ignore_hidden => 1)->query($dir, qr/^b/i)`.\n"

i18n/Aion/Fs.ru-en.po  view on Meta::CPAN

"* [Mojo::File](https://metacpan.org/pod/Mojo::File) – `path($file)->remove`."
msgstr ""
"* `unlink` + `rmdir`.\n"
"* [File::Path](https://metacpan.org/pod/File::Path) – `remove_tree(\"dir\")`.\n"
"* [File::Path::Tiny](https://metacpan.org/pod/File::Path::Tiny) – `File::Path::Tiny::rm($path)`. Does not throw exceptions.\n"
"* [Mojo::File](https://metacpan.org/pod/Mojo::File) – `path($file)->remove`."

msgid "Заменяет каждый файл на `$_`, если его изменяет `&sub`. Возвращает файлы, в которых не было замен."
msgstr "Replaces each file with `$_` if it is modified by `&sub`. Returns files that have no replacements."

msgid "`@files` может содержать массивы из двух элементов. Первый рассматривается как путь, а второй – как слой. Слой по умолчанию – `:utf8`."
msgstr "`@files` can contain arrays of two elements. The first is considered as a path, and the second as a layer. The default layer is `:utf8`."

msgid "`&sub` вызывается для каждого файла из `@files`. В неё передаются:"
msgstr "`&sub` is called for each file in `@files`. It transmits:"

msgid ""
"* `$_` – содержимое файла.\n"
"* `$a` – путь к файлу.\n"
"* `$b` – слой которым был считан файл и которым он будет записан."
msgstr ""
"* `$_` – file contents.\n"
"* `$a` – path to the file.\n"
"* `$b` – the layer with which the file was read and with which it will be written."

msgid "В примере ниже файл \"replace.ex\" считывается слоем `:utf8`, а записывается слоем `:raw` в функции `replace`:"
msgstr "In the example below, the file \"replace.ex\" is read by the `:utf8` layer and written by the `:raw` layer in the `replace` function:"

msgid ""
"* [File::Edit](https://metacpan.org/pod/File::Edit) – `File::Edit->new($file)->replace('x', 'y')->save`.\n"
"* [File::Edit::Portable](https://metacpan.org/pod/File::Edit::Portable) – `File::Edit::Portable->new->splice(file => $file, line => 10, contens => [\"line1\", \"line2\"])`.\n"
"* [File::Replace](https://metacpan.org/pod/File::Replace) – `($infh,$outfh,$repl) = replace3($file); while (<$infh>) { print $outfh \"X: $_\" } $repl->finish`.\n"
"* [File::Replace::Inplace](https://metacpan.org/pod/File::Replace::Inplace)."
msgstr ""
"* [File::Edit](https://metacpan.org/pod/File::Edit) – `File::Edit->new($file)->replace('x', 'y')->save`.\n"
"* [File::Edit::Portable](https://metacpan.org/pod/File::Edit::Portable) – `File::Edit::Portable->new->splice(file => $file, line => 10, contens => [\"line1\", \"line2\"])`.\n"
"* [File::Replace](https://metacpan.org/pod/File::Replace) – `($infh,$outfh,$repl) = replace3($file); while (<$infh>) { print $outfh \"X: $_\" } $repl->finish`.\n"
"* [File::Replace::Inplace](https://metacpan.org/pod/File::Replace::Inplace)."

msgid "Как **mkdir -p**, но считает последнюю часть пути (после последней косой черты) именем файла и не создаёт её каталогом. Без параметра исполÑ...
msgstr "Like **mkdir -p**, but considers the last part of the path (after the last slash) to be a filename and does not create it as a directory. Without a parameter, uses `$_`."

msgid ""
"* Если `$path` не указан, использует `$_`.\n"
"* Если `$path` является ссылкой на массив, тогда используется путь в качестве первого элемента и права в качестве второго элемента.\n"
"* Права по умолчанию – `0755`.\n"
"* Возвращает `$path`."

i18n/Aion/Fs.ru-en.po  view on Meta::CPAN


msgid "Файл lib/A.pm:"
msgstr "lib/A.pm file:"

msgid "Файл lib/N.pm:"
msgstr "lib/N.pm file:"

msgid "Считывает файл в первый раз. Любая последующая попытка считать этот файл возвращает `undef`. Используется для вставки модулей js и css в ре...
msgstr "Reads the file for the first time. Any subsequent attempt to read this file returns `undef`. Used to insert js and css modules into the resulting file. Without a parameter, uses `$_`."

msgid "* `$file` может содержать массивы из двух элементов. Первый рассматривается как путь, а второй – как слой. Слой по умолчанию – `:utf8`.\n"
"* Если `$file` не указан – использует `$_`."
msgstr "* `$file` can contain arrays of two elements. The first is considered as a path, and the second as a layer. The default layer is `:utf8`.\n"
"* If `$file` is not specified, use `$_`."

msgid "Переводит файловую маску в регулярное выражение. Без параметра использует `$_`."
msgstr "Converts a file mask to a regular expression. Without a parameter, uses `$_`."

msgid ""
"* `**` - `[^/]*`\n"
"* `*` - `.*`\n"
"* `?` - `.`\n"
"* `??` - `[^/]`\n"

lib/Aion/Fs.md  view on Meta::CPAN


[map cat, grep -f, find ["hello/big", "hello/small"]];  # --> [qw/ hellow! noenter /]

my @noreplaced = replace { s/h/$a $b H/ }
    find "hello", "-f", "*.txt", qr/\.txt$/, sub { /\.txt$/ },
        noenter "*small*",
            errorenter { warn "find $_: $!" };

\@noreplaced; # --> ["hello/moon.txt"]

cat "hello/world.txt";       # => hello/world.txt :utf8 Hi!
cat "hello/moon.txt";        # => noreplace
cat "hello/big/world.txt";   # => hello/big/world.txt :utf8 Hellow!
cat "hello/small/world.txt"; # => noenter

[find "hello", "*.txt"]; # --> [qw!  hello/moon.txt  hello/world.txt  hello/big/world.txt  hello/small/world.txt  !]

my @dirs;

my $iter = find "hello", "-d";

while(<$iter>) {
    push @dirs, $_;

lib/Aion/Fs.md  view on Meta::CPAN

# SUBROUTINES/METHODS

## cat ($file)

Считывает файл. Если параметр не указан, использует `$_`.

```perl
cat "/etc/passwd"  # ~> root
```

`cat` читает со слоем `:utf8`. Но можно указать другой слой следующим образом:

```perl
lay "unicode.txt", "↯";
length cat "unicode.txt"            # -> 1
length cat["unicode.txt", ":raw"]   # -> 3
```

`cat` вызывает исключение в случае ошибки операции ввода-вывода:

```perl

lib/Aion/Fs.md  view on Meta::CPAN

* [File::Util](https://metacpan.org/pod/File::Util) – `File::Util->new->load_file(file => 'file.txt')`.
* [IO::All](https://metacpan.org/pod/IO::All) – `io('file.txt') > $contents`.
* [IO::Util](https://metacpan.org/pod/IO::Util) – `$contents = ${ slurp 'file.txt' }`.
* [Mojo::File](https://metacpan.org/pod/Mojo::File) – `path($file)->slurp`.

## lay ($file?, $content)

Записывает `$content` в `$file`.

* Если указан один параметр, использует `$_` вместо `$file`.
* `lay`, использует слой `:utf8`. Для указания иного слоя используется массив из двух элементов в параметре `$file`:

```perl
lay "unicode.txt", "↯"  # => unicode.txt
lay ["unicode.txt", ":raw"], "↯"  # => unicode.txt

eval { lay "/", "↯" }; $@ # ~> lay /: Is a directory
```

### See also

lib/Aion/Fs.md  view on Meta::CPAN

$count # -> 3
```

### See also

* [AudioFile::Find](https://metacpan.org/pod/AudioFile::Find) – ищет аудиофайлы в указанной директории. Позволяет фильтровать их по атрибутам: названию, артисту, жа...
* [Directory::Iterator](https://metacpan.org/pod/Directory::Iterator) – `$it = Directory::Iterator->new($dir, %opts); push @paths, $_ while <$it>`.
* [IO::All](https://metacpan.org/pod/IO::All) – `@paths = map { "$_" } grep { -f $_ && $_->size > 10*1024 } io(".")->all(0)`.
* [IO::All::Rule](https://metacpan.org/pod/IO::All::Rule) – `$next = IO::All::Rule->new->file->size(">10k")->iter($dir1, $dir2); push @paths, "$f" while $f = $next->()`.
* [File::Find](https://metacpan.org/pod/File::Find) – `find( sub { push @paths, $File::Find::name if /\.png/ }, $dir )`.
* [File::Find::utf8](https://metacpan.org/pod/File::Find::utf8) – как [File::Find](https://metacpan.org/pod/File::Find), только пути файлов в _utf8_.
* [File::Find::Age](https://metacpan.org/pod/File::Find::Age) – сортирует файлы по времени модификации (наследует [File::Find::Rule](https://metacpan.org/pod/File::Find::Rule)): `File::Find::Age->in($dir1,...
* [File::Find::Declare](https://metacpan.org/pod/File::Find::Declare) – `@paths = File::Find::Declare->new({ size => '>10K', perms => 'wr-wr-wr-', modified => '<2010-01-30', recurse => 1, dirs => [$dir1] })->find`.
* [File::Find::Iterator](https://metacpan.org/pod/File::Find::Iterator) – имеет ООП интерфейс с итератором и функции `imap` и `igrep`.
* [File::Find::Match](https://metacpan.org/pod/File::Find::Match) – вызывает обработчик на каждый подошедший фильтр. Похож на `switch`.
* [File::Find::Node](https://metacpan.org/pod/File::Find::Node) – обходит иерархию файлов параллельно несколькими процессами: `tie @paths, IPC::Shareable, { key => "GLUE STRING", create => 1 }; F...
* [File::Find::Fast](https://metacpan.org/pod/File::Find::Fast) – `@paths = @{ find($dir) }`.
* [File::Find::Object](https://metacpan.org/pod/File::Find::Object) – имеет ООП интерфейс с итератором.
* [File::Find::Parallel](https://metacpan.org/pod/File::Find::Parallel) – умеет сравнивать два каталога и возвращать их объединение, пересечение и количественное перес...
* [File::Find::Random](https://metacpan.org/pod/File::Find::Random) – выбирает файл или директорию наугад из иерархии файлов.
* [File::Find::Rex](https://metacpan.org/pod/File::Find::Rex) – `@paths = File::Find::Rex->new(recursive => 1, ignore_hidden => 1)->query($dir, qr/^b/i)`.

lib/Aion/Fs.md  view on Meta::CPAN


* `unlink` + `rmdir`.
* [File::Path](https://metacpan.org/pod/File::Path) – `remove_tree("dir")`.
* [File::Path::Tiny](https://metacpan.org/pod/File::Path::Tiny) – `File::Path::Tiny::rm($path)`. Не выбрасывает исключений.
* [Mojo::File](https://metacpan.org/pod/Mojo::File) – `path($file)->remove`.

## replace (&sub, @files)

Заменяет каждый файл на `$_`, если его изменяет `&sub`. Возвращает файлы, в которых не было замен.

`@files` может содержать массивы из двух элементов. Первый рассматривается как путь, а второй – как слой. Слой по умолчанию – `:utf8`.

`&sub` вызывается для каждого файла из `@files`. В неё передаются:

* `$_` – содержимое файла.
* `$a` – путь к файлу.
* `$b` – слой которым был считан файл и которым он будет записан.

В примере ниже файл "replace.ex" считывается слоем `:utf8`, а записывается слоем `:raw` в функции `replace`:

```perl
local $_ = "replace.ex";
lay "abc";
replace { $b = ":utf8"; y/a/¡/ } [$_, ":raw"];
cat  # => ¡bc
```

### See also

* [File::Edit](https://metacpan.org/pod/File::Edit) – `File::Edit->new($file)->replace('x', 'y')->save`.
* [File::Edit::Portable](https://metacpan.org/pod/File::Edit::Portable) – `File::Edit::Portable->new->splice(file => $file, line => 10, contens => ["line1", "line2"])`.
* [File::Replace](https://metacpan.org/pod/File::Replace) – `($infh,$outfh,$repl) = replace3($file); while (<$infh>) { print $outfh "X: $_" } $repl->finish`.
* [File::Replace::Inplace](https://metacpan.org/pod/File::Replace::Inplace).

## mkpath (;$path)

Как **mkdir -p**, но считает последнюю часть пути (после последней косой черты) именем файла и не создаёт её каталогом. Без параметра используе...

* Если `$path` не указан, использует `$_`.
* Если `$path` является ссылкой на массив, тогда используется путь в качестве первого элемента и права в качестве второго элемента.
* Права по умолчанию – `0755`.
* Возвращает `$path`.

lib/Aion/Fs.md  view on Meta::CPAN

use lib "lib";
include("A")->new               # ~> A=HASH\(0x\w+\)
[map include, qw/A N/]          # --> [qw/A N/]
{ local $_="N"; include->ex }   # -> 123
```

## catonce (;$file)

Считывает файл в первый раз. Любая последующая попытка считать этот файл возвращает `undef`. Используется для вставки модулей js и css в резулÑ...

* `$file` может содержать массивы из двух элементов. Первый рассматривается как путь, а второй – как слой. Слой по умолчанию – `:utf8`.
* Если `$file` не указан – использует `$_`.

```perl
local $_ = "catonce.txt";
lay "result";
catonce  # -> "result"
catonce  # -> undef

eval { catonce[] }; $@ # ~> catonce not use ref path!
```

lib/Aion/Fs.pm  view on Meta::CPAN

			mkdir $cat, $permission or ($! != FILE_EXISTS? die "mkpath $cat: $!": ());
		}
	}
	
	$path
}

# Считать файл
sub cat(;$) {
    my ($file) = @_ == 0? $_: @_;
	my $layer = ":utf8";
	($file, $layer) = @$file if ref $file;
	open my $f, "<$layer", $file or die "cat $file: $!";
	read $f, my $x, -s $f;
	close $f;
	$x
}

# Записать файл
sub lay ($;$) {
	my ($file, $s) = @_ == 1? ($_, @_): @_;
	my $layer = ":utf8";
	($file, $layer) = @$file if ref $file;
	open my $f, ">$layer", $file or die "lay $file: $!";
	local $\;
	print $f $s;
	close $f;
	$file
}

# Считать файл, если он ещё не был считан
our %FILE_INC;

lib/Aion/Fs.pm  view on Meta::CPAN

sub find_stop() {
	die bless {}, "Aion::Fs::stop"
}

# Производит замену во всех указанных файлах. Возвращает файлы в которых замен не было
sub replace(&@) {
    my $fn = shift;
	my @noreplace; local $_; my $pkg = caller;
	my $aref = "${pkg}::a";	my $bref = "${pkg}::b";
    for $$aref (@_) {
		if(ref $$aref) { ($$aref, $$bref) = @$$aref } else { $$bref = ":utf8" }
        my $file = $_ = cat [$$aref, $$bref];
        $fn->();
		if($file ne $_) { lay [$$aref, $$bref], $_ } else { push @noreplace, $$aref if defined wantarray }
    }
	@noreplace
}

# Стирает все указанные файлы. Возвращает переданные файлы
sub erase(@) {
    -d? rmdir: unlink or die "erase ${\(-d? 'dir': 'file')} $_: $!" for @_;

lib/Aion/Fs.pm  view on Meta::CPAN

	my $path = from_pkg $pkg;
	return $pkg if exists $INC{$path};
	require $path;
	$pkg
}

1;

__END__

=encoding utf-8

=head1 NAME

Aion::Fs - utilities for the file system: reading, writing, searching, replacing files, etc.

=head1 VERSION

0.2.2

=head1 SYNOPSIS

lib/Aion/Fs.pm  view on Meta::CPAN

	
	[map cat, grep -f, find ["hello/big", "hello/small"]];  # --> [qw/ hellow! noenter /]
	
	my @noreplaced = replace { s/h/$a $b H/ }
	    find "hello", "-f", "*.txt", qr/\.txt$/, sub { /\.txt$/ },
	        noenter "*small*",
	            errorenter { warn "find $_: $!" };
	
	\@noreplaced; # --> ["hello/moon.txt"]
	
	cat "hello/world.txt";       # => hello/world.txt :utf8 Hi!
	cat "hello/moon.txt";        # => noreplace
	cat "hello/big/world.txt";   # => hello/big/world.txt :utf8 Hellow!
	cat "hello/small/world.txt"; # => noenter
	
	[find "hello", "*.txt"]; # --> [qw!  hello/moon.txt  hello/world.txt  hello/big/world.txt  hello/small/world.txt  !]
	
	my @dirs;
	
	my $iter = find "hello", "-d";
	
	while(<$iter>) {
	    push @dirs, $_;

lib/Aion/Fs.pm  view on Meta::CPAN

=back

=head1 SUBROUTINES/METHODS

=head2 cat ($file)

Reads the file. If no parameter is specified, use C<$_>.

	cat "/etc/passwd"  # ~> root

C<cat> reads with layer C<:utf8>. But you can specify another layer like this:

	lay "unicode.txt", "↯";
	length cat "unicode.txt"            # -> 1
	length cat["unicode.txt", ":raw"]   # -> 3

C<cat> throws an exception if the I/O operation fails:

	eval { cat "A" }; $@  # ~> cat A: No such file or directory

=head3 See also

lib/Aion/Fs.pm  view on Meta::CPAN

=back

=head2 lay ($file?, $content)

Writes C<$content> to C<$file>.

=over

=item * If one parameter is specified, use C<$_> instead of C<$file>.

=item * C<lay>, uses the C<:utf8> layer. To specify a different layer, use an array of two elements in the C<$file> parameter:

=back

	lay "unicode.txt", "↯"  # => unicode.txt
	lay ["unicode.txt", ":raw"], "↯"  # => unicode.txt
	
	eval { lay "/", "↯" }; $@ # ~> lay /: Is a directory

=head3 See also

lib/Aion/Fs.pm  view on Meta::CPAN

=item * L<AudioFile::Find> – searches for audio files in the specified directory. Allows you to filter them by attributes: title, artist, genre, album and track.

=item * L<Directory::Iterator> – C<< $it = Directory::Iterator-E<gt>new($dir, %opts); push @paths, $_ while E<lt>$itE<gt> >>.

=item * L<IO::All> – C<< @paths = map { "$_" } grep { -f $_ && $_-E<gt>size E<gt> 10*1024 } io(".")-E<gt>all(0) >>.

=item * L<IO::All::Rule> – C<< $next = IO::All::Rule-E<gt>new-E<gt>file-E<gt>size("E<gt>10k")-E<gt>iter($dir1, $dir2); push @paths, "$f" while $f = $next-E<gt>() >>.

=item * L<File::Find> – C<find( sub { push @paths, $File::Find::name if /\.png/ }, $dir )>.

=item * L<File::Find::utf8> – like L<File::Find>, only file paths are in I<utf8>.

=item * L<File::Find::Age> – sorts files by modification time (inherits L<File::Find::Rule>): C<< File::Find::Age-E<gt>in($dir1, $dir2) >>.

=item * L<File::Find::Declare> – C<< @paths = File::Find::Declare-E<gt>new({ size =E<gt> 'E<gt>10K', perms =E<gt> 'wr-wr-wr-', modified =E<gt> 'E<lt>2010-01-30', recurse =E<gt> 1, dirs =E<gt> [$dir1] })-E<gt>find >>.

=item * L<File::Find::Iterator> – has an OOP interface with an iterator and the C<imap> and C<igrep> functions.

=item * L<File::Find::Match> – calls a handler for each matching filter. Similar to C<switch>.

=item * L<File::Find::Node> – traverses the file hierarchy in parallel by several processes: C<< tie @paths, IPC::Shareable, { key =E<gt> "GLUE STRING", create =E<gt> 1 }; File::Find::Node-E<gt>new(".")-E<gt>process(sub { my $f = shift; $f-E<gt>for...

lib/Aion/Fs.pm  view on Meta::CPAN

=item * L<File::Path::Tiny> – C<File::Path::Tiny::rm($path)>. Does not throw exceptions.

=item * L<Mojo::File> – C<< path($file)-E<gt>remove >>.

=back

=head2 replace (&sub, @files)

Replaces each file with C<$_> if it is modified by C<&sub>. Returns files that have no replacements.

C<@files> can contain arrays of two elements. The first is considered as a path, and the second as a layer. The default layer is C<:utf8>.

C<&sub> is called for each file in C<@files>. It transmits:

=over

=item * C<$_> – file contents.

=item * C<$a> – path to the file.

=item * C<$b> – the layer with which the file was read and with which it will be written.

=back

In the example below, the file "replace.ex" is read by the C<:utf8> layer and written by the C<:raw> layer in the C<replace> function:

	local $_ = "replace.ex";
	lay "abc";
	replace { $b = ":utf8"; y/a/¡/ } [$_, ":raw"];
	cat  # => ¡bc

=head3 See also

=over

=item * L<File::Edit> – C<< File::Edit-E<gt>new($file)-E<gt>replace('x', 'y')-E<gt>save >>.

=item * L<File::Edit::Portable> – C<< File::Edit::Portable-E<gt>new-E<gt>splice(file =E<gt> $file, line =E<gt> 10, contens =E<gt> ["line1", "line2"]) >>.

=item * L<File::Replace> – C<< ($infh,$outfh,$repl) = replace3($file); while (E<lt>$infhE<gt>) { print $outfh "X: $_" } $repl-E<gt>finish >>.

=item * L<File::Replace::Inplace>.

=back

=head2 mkpath (;$path)

Like B<mkdir -p>, but considers the last part of the path (after the last slash) to be a filename and does not create it as a directory. Without a parameter, uses C<$_>.

=over

lib/Aion/Fs.pm  view on Meta::CPAN

	include("A")->new               # ~> A=HASH\(0x\w+\)
	[map include, qw/A N/]          # --> [qw/A N/]
	{ local $_="N"; include->ex }   # -> 123

=head2 catonce (;$file)

Reads the file for the first time. Any subsequent attempt to read this file returns C<undef>. Used to insert js and css modules into the resulting file. Without a parameter, uses C<$_>.

=over

=item * C<$file> can contain arrays of two elements. The first is considered as a path, and the second as a layer. The default layer is C<:utf8>.

=item * If C<$file> is not specified, use C<$_>.

=back

	local $_ = "catonce.txt";
	lay "result";
	catonce  # -> "result"
	catonce  # -> undef
	

lib/Aion/Fs/Find.pm  view on Meta::CPAN

		die if ref $@ ne "Aion::Fs::stop";
	}

	$path
}

1;

__END__

=encoding utf-8

=head1 NAME

Aion::Fs::Find - file search iterator for Aion::Fs#find

=head1 SYNOPSIS

	use Aion::Fs::Find;
	
	my $iter = Aion::Fs::Find->new(

t/aion/fs.t  view on Meta::CPAN

use common::sense; use open qw/:std :utf8/;  use Carp qw//; use Cwd qw//; use File::Basename qw//; use File::Find qw//; use File::Slurper qw//; use File::Spec qw//; use File::Path qw//; use Scalar::Util qw//;  use Test::More 0.98;  BEGIN { 	$SIG{__DI...
# # NAME
# 
# Aion::Fs - утилиты для файловой системы: чтение, запись, поиск, замена файлов и т.д.
# 
# # VERSION
# 
# 0.2.1
# 
# # SYNOPSIS
# 

t/aion/fs.t  view on Meta::CPAN


::is_deeply scalar do {[map cat, grep -f, find ["hello/big", "hello/small"]];}, scalar do {[qw/ hellow! noenter /]}, '[map cat, grep -f, find ["hello/big", "hello/small"]];  # --> [qw/ hellow! noenter /]';

my @noreplaced = replace { s/h/$a $b H/ }
    find "hello", "-f", "*.txt", qr/\.txt$/, sub { /\.txt$/ },
        noenter "*small*",
            errorenter { warn "find $_: $!" };

::is_deeply scalar do {\@noreplaced;}, scalar do {["hello/moon.txt"]}, '\@noreplaced; # --> ["hello/moon.txt"]';

::is scalar do {cat "hello/world.txt";}, "hello/world.txt :utf8 Hi!", 'cat "hello/world.txt";       # => hello/world.txt :utf8 Hi!';
::is scalar do {cat "hello/moon.txt";}, "noreplace", 'cat "hello/moon.txt";        # => noreplace';
::is scalar do {cat "hello/big/world.txt";}, "hello/big/world.txt :utf8 Hellow!", 'cat "hello/big/world.txt";   # => hello/big/world.txt :utf8 Hellow!';
::is scalar do {cat "hello/small/world.txt";}, "noenter", 'cat "hello/small/world.txt"; # => noenter';

::is_deeply scalar do {[find "hello", "*.txt"];}, scalar do {[qw!  hello/moon.txt  hello/world.txt  hello/big/world.txt  hello/small/world.txt  !]}, '[find "hello", "*.txt"]; # --> [qw!  hello/moon.txt  hello/world.txt  hello/big/world.txt  hello/sma...

my @dirs;

my $iter = find "hello", "-d";

while(<$iter>) {
    push @dirs, $_;

t/aion/fs.t  view on Meta::CPAN

# # SUBROUTINES/METHODS
# 
# ## cat ($file)
# 
# Считывает файл. Если параметр не указан, использует `$_`.
# 
::done_testing; }; subtest 'cat ($file)' => sub { 
::like scalar do {cat "/etc/passwd"}, qr{root}, 'cat "/etc/passwd"  # ~> root';

# 
# `cat` читает со слоем `:utf8`. Но можно указать другой слой следующим образом:
# 

lay "unicode.txt", "↯";
::is scalar do {length cat "unicode.txt"}, scalar do{1}, 'length cat "unicode.txt"            # -> 1';
::is scalar do {length cat["unicode.txt", ":raw"]}, scalar do{3}, 'length cat["unicode.txt", ":raw"]   # -> 3';

# 
# `cat` вызывает исключение в случае ошибки операции ввода-вывода:
# 

t/aion/fs.t  view on Meta::CPAN

# * [File::Util](https://metacpan.org/pod/File::Util) – `File::Util->new->load_file(file => 'file.txt')`.
# * [IO::All](https://metacpan.org/pod/IO::All) – `io('file.txt') > $contents`.
# * [IO::Util](https://metacpan.org/pod/IO::Util) – `$contents = ${ slurp 'file.txt' }`.
# * [Mojo::File](https://metacpan.org/pod/Mojo::File) – `path($file)->slurp`.
# 
# ## lay ($file?, $content)
# 
# Записывает `$content` в `$file`.
# 
# * Если указан один параметр, использует `$_` вместо `$file`.
# * `lay`, использует слой `:utf8`. Для указания иного слоя используется массив из двух элементов в параметре `$file`:
# 
::done_testing; }; subtest 'lay ($file?, $content)' => sub { 
::is scalar do {lay "unicode.txt", "↯"}, "unicode.txt", 'lay "unicode.txt", "↯"  # => unicode.txt';
::is scalar do {lay ["unicode.txt", ":raw"], "↯"}, "unicode.txt", 'lay ["unicode.txt", ":raw"], "↯"  # => unicode.txt';

::like scalar do {eval { lay "/", "↯" }; $@}, qr{lay /: Is a directory}, 'eval { lay "/", "↯" }; $@ # ~> lay /: Is a directory';

# 
# ### See also
# 

t/aion/fs.t  view on Meta::CPAN

::is scalar do {$count}, scalar do{3}, '$count # -> 3';

# 
# ### See also
# 
# * [AudioFile::Find](https://metacpan.org/pod/AudioFile::Find) – ищет аудиофайлы в указанной директории. Позволяет фильтровать их по атрибутам: названию, артисту, ж...
# * [Directory::Iterator](https://metacpan.org/pod/Directory::Iterator) – `$it = Directory::Iterator->new($dir, %opts); push @paths, $_ while <$it>`.
# * [IO::All](https://metacpan.org/pod/IO::All) – `@paths = map { "$_" } grep { -f $_ && $_->size > 10*1024 } io(".")->all(0)`.
# * [IO::All::Rule](https://metacpan.org/pod/IO::All::Rule) – `$next = IO::All::Rule->new->file->size(">10k")->iter($dir1, $dir2); push @paths, "$f" while $f = $next->()`.
# * [File::Find](https://metacpan.org/pod/File::Find) – `find( sub { push @paths, $File::Find::name if /\.png/ }, $dir )`.
# * [File::Find::utf8](https://metacpan.org/pod/File::Find::utf8) – как [File::Find](https://metacpan.org/pod/File::Find), только пути файлов в _utf8_.
# * [File::Find::Age](https://metacpan.org/pod/File::Find::Age) – сортирует файлы по времени модификации (наследует [File::Find::Rule](https://metacpan.org/pod/File::Find::Rule)): `File::Find::Age->in($dir...
# * [File::Find::Declare](https://metacpan.org/pod/File::Find::Declare) – `@paths = File::Find::Declare->new({ size => '>10K', perms => 'wr-wr-wr-', modified => '<2010-01-30', recurse => 1, dirs => [$dir1] })->find`.
# * [File::Find::Iterator](https://metacpan.org/pod/File::Find::Iterator) – имеет ООП интерфейс с итератором и функции `imap` и `igrep`.
# * [File::Find::Match](https://metacpan.org/pod/File::Find::Match) – вызывает обработчик на каждый подошедший фильтр. Похож на `switch`.
# * [File::Find::Node](https://metacpan.org/pod/File::Find::Node) – обходит иерархию файлов параллельно несколькими процессами: `tie @paths, IPC::Shareable, { key => "GLUE STRING", create => 1 };...
# * [File::Find::Fast](https://metacpan.org/pod/File::Find::Fast) – `@paths = @{ find($dir) }`.
# * [File::Find::Object](https://metacpan.org/pod/File::Find::Object) – имеет ООП интерфейс с итератором.
# * [File::Find::Parallel](https://metacpan.org/pod/File::Find::Parallel) – умеет сравнивать два каталога и возвращать их объединение, пересечение и количественное пере...
# * [File::Find::Random](https://metacpan.org/pod/File::Find::Random) – выбирает файл или директорию наугад из иерархии файлов.
# * [File::Find::Rex](https://metacpan.org/pod/File::Find::Rex) – `@paths = File::Find::Rex->new(recursive => 1, ignore_hidden => 1)->query($dir, qr/^b/i)`.

t/aion/fs.t  view on Meta::CPAN

# 
# * `unlink` + `rmdir`.
# * [File::Path](https://metacpan.org/pod/File::Path) – `remove_tree("dir")`.
# * [File::Path::Tiny](https://metacpan.org/pod/File::Path::Tiny) – `File::Path::Tiny::rm($path)`. Не выбрасывает исключений.
# * [Mojo::File](https://metacpan.org/pod/Mojo::File) – `path($file)->remove`.
# 
# ## replace (&sub, @files)
# 
# Заменяет каждый файл на `$_`, если его изменяет `&sub`. Возвращает файлы, в которых не было замен.
# 
# `@files` может содержать массивы из двух элементов. Первый рассматривается как путь, а второй – как слой. Слой по умолчанию – `:utf8`.
# 
# `&sub` вызывается для каждого файла из `@files`. В неё передаются:
# 
# * `$_` – содержимое файла.
# * `$a` – путь к файлу.
# * `$b` – слой которым был считан файл и которым он будет записан.
# 
# В примере ниже файл "replace.ex" считывается слоем `:utf8`, а записывается слоем `:raw` в функции `replace`:
# 
::done_testing; }; subtest 'replace (&sub, @files)' => sub { 
local $_ = "replace.ex";
lay "abc";
replace { $b = ":utf8"; y/a/¡/ } [$_, ":raw"];
::is scalar do {cat}, "¡bc", 'cat  # => ¡bc';

# 
# ### See also
# 
# * [File::Edit](https://metacpan.org/pod/File::Edit) – `File::Edit->new($file)->replace('x', 'y')->save`.
# * [File::Edit::Portable](https://metacpan.org/pod/File::Edit::Portable) – `File::Edit::Portable->new->splice(file => $file, line => 10, contens => ["line1", "line2"])`.
# * [File::Replace](https://metacpan.org/pod/File::Replace) – `($infh,$outfh,$repl) = replace3($file); while (<$infh>) { print $outfh "X: $_" } $repl->finish`.
# * [File::Replace::Inplace](https://metacpan.org/pod/File::Replace::Inplace).
# 
# ## mkpath (;$path)
# 
# Как **mkdir -p**, но считает последнюю часть пути (после последней косой черты) именем файла и не создаёт её каталогом. Без параметра использу...
# 
# * Если `$path` не указан, использует `$_`.
# * Если `$path` является ссылкой на массив, тогда используется путь в качестве первого элемента и права в качестве второго элемента.
# * Права по умолчанию – `0755`.
# * Возвращает `$path`.

t/aion/fs.t  view on Meta::CPAN

use lib "lib";
::like scalar do {include("A")->new}, qr{A=HASH\(0x\w+\)}, 'include("A")->new               # ~> A=HASH\(0x\w+\)';
::is_deeply scalar do {[map include, qw/A N/]}, scalar do {[qw/A N/]}, '[map include, qw/A N/]          # --> [qw/A N/]';
::is scalar do {{ local $_="N"; include->ex }}, scalar do{123}, '{ local $_="N"; include->ex }   # -> 123';

# 
# ## catonce (;$file)
# 
# Считывает файл в первый раз. Любая последующая попытка считать этот файл возвращает `undef`. Используется для вставки модулей js и css в резуÐ...
# 
# * `$file` может содержать массивы из двух элементов. Первый рассматривается как путь, а второй – как слой. Слой по умолчанию – `:utf8`.
# * Если `$file` не указан – использует `$_`.
# 
::done_testing; }; subtest 'catonce (;$file)' => sub { 
local $_ = "catonce.txt";
lay "result";
::is scalar do {catonce}, scalar do{"result"}, 'catonce  # -> "result"';
::is scalar do {catonce}, scalar do{undef}, 'catonce  # -> undef';

::like scalar do {eval { catonce[] }; $@}, qr{catonce not use ref path\!}, 'eval { catonce[] }; $@ # ~> catonce not use ref path!';

t/aion/fs/find.t  view on Meta::CPAN

use common::sense; use open qw/:std :utf8/;  use Carp qw//; use Cwd qw//; use File::Basename qw//; use File::Find qw//; use File::Slurper qw//; use File::Spec qw//; use File::Path qw//; use Scalar::Util qw//;  use Test::More 0.98;  BEGIN { 	$SIG{__DI...
# # NAME
# 
# Aion::Fs::Find - итератор поиска файлов для Aion::Fs#find
# 
# # SYNOPSIS
# 
subtest 'SYNOPSIS' => sub { 
use Aion::Fs::Find;

my $iter = Aion::Fs::Find->new(



( run in 0.695 second using v1.01-cache-2.11-cpan-9ff20fc0ed8 )