Aion-Fs

 view release on metacpan or  search on metacpan

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

mtime "hello";  # ~> ^\d+(\.\d+)?$

[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, $_;
}

\@dirs; # --> [qw!  hello  hello/big hello/small  !]

erase reverse find "hello";

-e "hello";  # -> undef
```

# DESCRIPTION

Этот модуль облегчает использование файловой системы.

Модули `File::Path`, `File::Slurper` и
`File::Find` обременены различными возможностями, которые используются редко, но требуют времени на ознакомление и тем самым повышают порог Ð...

В `Aion::Fs` же использован принцип программирования KISS - чем проще, тем лучше!

Супермодуль `IO::All` не является конкурентом `Aion::Fs`, т.к. использует ООП подход, а `Aion::Fs` – ФП.

* ООП – объектно-ориентированное программирование.
* ФП – функциональное программирование.

# 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
eval { cat "A" }; $@  # ~> cat A: No such file or directory
```

### See also

* [autodie](https://metacpan.org/pod/autodie) – `open $f, "r.txt"; $s = join "", <$f>; close $f`.
* [File::Slurp](https://metacpan.org/pod/File::Slurp) – `read_file('file.txt')`.
* [File::Slurper](https://metacpan.org/pod/File::Slurper) – `read_text('file.txt')`, `read_binary('file.txt')`.
* [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

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

## find (;$path, @filters)

Рекурсивно обходит и возвращает пути из указанного пути или путей, если `$path` является ссылкой на массив. Без параметров использует `$_` каÐ...

Фильтры могут быть:

* Подпрограммой – путь к текущему файлу передаётся в `$_`, а подпрограмма должна вернуть истину или ложь, как они понимаются perl-ом.
* Regexp – тестирует каждый путь регулярным выражением.
* Строка в виде "-Xxx", где `Xxx` – один или несколько символов. Аналогична операторам perl-а для тестирования файлов. Пример: `-fr` проверяет путь Ñ...
* Остальные строки превращаются функцией `wildcard` (см. ниже) в регулярное выражение для проверки каждого пути.

Пути, не прошедшие проверку `@filters`, не возвращаются.

Если фильтр -X не является файловой функцией perl, то выбрасывается исключение:

```perl
eval { find "example", "-h" }; $@   # ~> Undefined subroutine &Aion::Fs::h called
```

Ð’ этом примере `find` не может войти в подкаталог и передаёт ошибку в функцию `errorenter` (см. ниже) с установленными переменными `$_` и `$!` (путём к Ð...

**Внимание!** Если `errorenter` не указана, то все ошибки **игнорируются**!

```perl
mkpath ["example/", 0];

[find "example"]                  # --> ["example"]
[find "example", noenter "-d"]    # --> ["example"]

eval { find "example", errorenter { die "find $_: $!" } }; $@   # ~> find example: Permission denied

mkpath for qw!ex/1/11 ex/1/12 ex/2/21 ex/2/22!;

my $count = 0;
find "ex", sub { find_stop if ++$count == 3; 1};
$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_.



( run in 0.630 second using v1.01-cache-2.11-cpan-f56aa216473 )