📜 ⬆️ ⬇️

Perl 6 File Operations

Directories


Instead of opendir and his friends, Perl 6 has one function dir, which 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, to use grep based on the results:

  > 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 


Lightweight

File :: Find


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

Example:

 find(:dir<t/dir1>, :type<file>, :name(/foo/)) 


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

Useful idioms


Create a new file

 open('new', :w).close 


Unnamed File Handler

  given open('foo', :w) { .say(' !'); .close } 

Source: https://habr.com/ru/post/252509/


All Articles