File Operations in Perl 6

Original author: Moritz
  • Transfer

Directories


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 Configure.pl README dynext t src tools CREDITS LICENSE Test.pm
    > dir 't'
    00-parrot 02-embed spec harness 01-sanity pmc spectest.data


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

    > dir 'src/core', test => any(/^C/, /^P/)
    Parcel.pm Cool.pm Parameter.pm Code.pm Complex.pm CallFrame.pm Positional.pm Capture.pm Pair.pm Cool-num.pm Callable.pm Cool-str.pm


Directories are created via mkdir ('foo')

Files


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

    > slurp 'VERSION'
    2010.11


There is access to the classical methods:

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


File checks


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

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


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.

Example:

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('Всем привет!');
            .close
        }

Also popular now: