File Operations in Perl 6

Original author: Moritz
  • Transfer


Instead of opendir and his friends, in Perl 6 there is one dir function that returns a list of files from a directory (by default, from the current one). Instead of a thousand words:

    # в директории Rakudo 
    > dir
    build parrot_install Makefile VERSION parrot docs README dynext t src tools CREDITS LICENSE
    > dir 't'
    00-parrot 02-embed spec harness 01-sanity pmc

Dir has an optional test parameter, for using grep according to the results of work:

    > dir 'src/core', test => any(/^C/, /^P/)

Directories are created via mkdir ('foo')


The easiest way to read a file in Perl 6 is slurp. It returns the contents of the file as a String.

    > slurp 'VERSION'

There is access to the classical methods:

    > my $fh = open 'CREDITS'
    > $fh.getc # читает символ
    > $fh.get # читает строчку
    > $fh.close; $fh = open 'new', :w # открывает на запись
    > $fh.print('foo   Bool::True
    > $fh.say('bar   Bool::True
    > $fh.close; say slurp('new')

File checks

File checks for existence and types go through smart matching ~~

    > 'LICENSE'.IO ~~ :e # есть ли файл?
    > 'LICENSE'.IO ~~ :d # а не директория ли это часом?
    > 'LICENSE'.IO ~~ :f # ну значит файл?

Light weight.

File :: Find

When standard functions end, modules are connected to business. File :: Find from the File :: Tools collection goes through the directory tree in search of the necessary files and creates lazy lists of found ones. It comes bundled with the Rakudo Star and is easy to install via neutro.


find(:dir, :type, :name(/foo/)) 

will produce a lazy list of files, and only files, in the t / dir1 directory with a name suitable for the / foo / regularity. List items are not simple lines. These are objects that turn into strings with a full path, but at the same time they have accessors for the name of the directory in which they lie (dir) and the file name (name). See the documentation for more details.

Useful Idioms

Create a new file

open('new', :w).close

Nameless file handler

        given open('foo', :w) {
            .say('Всем привет!');

Also popular now: