1IO::All(3)            User Contributed Perl Documentation           IO::All(3)
2
3
4

NAME

6       IO::All - IO::All to Larry Wall!
7

VERSION

9       This document describes IO::All version 0.87.
10

SYNOPSIS

12       First, some safe examples:
13
14           use IO::All;
15
16           # Some of the many ways to read a whole file into a scalar
17           $contents = io->file('file.txt')->slurp;    # Read an entire file
18           @files    = io->dir('lib')->all;            # Get a list of files
19           $tail     = io->pipe('-| tail app.log');    # Open a pipe to a command
20           $line     = $tail->getline;                 # Read from the pipe
21
22       That said, there are a lot more things that are very convenient and
23       will help you write code very quickly, though they should be used
24       judiciously:
25
26           use IO::All;                                # Let the madness begin...
27
28           # Some of the many ways to read a whole file into a scalar
29           io('file.txt') > $contents;                 # Overloaded "arrow"
30           $contents < io 'file.txt';                  # Flipped but same operation
31           $io = io 'file.txt';                        # Create a new IO::All object
32           $contents = $$io;                           # Overloaded scalar dereference
33           $contents = $io->all;                       # A method to read everything
34           $contents = $io->slurp;                     # Another method for that
35           $contents = join '', $io->getlines;         # Join the separate lines
36           $contents = join '', map "$_\n", @$io;      # Same. Overloaded array deref
37           $io->tie;                                   # Tie the object as a handle
38           $contents = join '', <$io>;                 # And use it in builtins
39           # and the list goes on ...
40
41           # Other file operations:
42           @lines = io('file.txt')->slurp;             # List context slurp
43           $content > io('file.txt');                  # Print to a file
44           io('file.txt')->print($content, $more);     # (ditto)
45           $content >> io('file.txt');                 # Append to a file
46           io('file.txt')->append($content);           # (ditto)
47           $content << $io;                            # Append to a string
48           io('copy.txt') < io('file.txt');            $ Copy a file
49           io('file.txt') > io('copy.txt');            # Invokes File::Copy
50           io('more.txt') >> io('all.txt');            # Add on to a file
51           io('dir/') < io('file.txt');                $ Copy a file to a directory
52           io('file.txt') > io('dir/');                # Invokes File::Copy
53           io('more.txt') >> io('dir/');               # Add on to a file in the dir
54
55           # UTF-8 Support
56           $contents = io('file.txt')->utf8->all;      # Turn on utf8
57           use IO::All -utf8;                          # Turn on utf8 for all io
58           $contents = io('file.txt')->all;            #   by default in this package.
59
60           # General Encoding Support
61           $contents = io('file.txt')->encoding('big5')->all;
62           use IO::All -encoding => 'big5';            # Turn on big5 for all io
63           $contents = io('file.txt')->all;            #   by default in this package.
64
65           # Print the path name of a file:
66           print $io->name;                            # The direct method
67           print "$io";                                # Object stringifies to name
68           print $io;                                  # Quotes not needed here
69           print $io->filename;                        # The file portion only
70           $io->os('win32');                           # change the object to be a
71                                                       # win32 path
72           print $io->ext;                             # The file extension only
73           print $io->mimetype;                        # The mimetype, requires a
74                                                       #  working File::MimeType
75
76
77           # Read all the files/directories in a directory:
78           $io = io('my/directory/');                  # Create new directory object
79           @contents = $io->all;                       # Get all contents of dir
80           @contents = @$io;                           # Directory as an array
81           @contents = values %$io;                    # Directory as a hash
82           push @contents, $subdir                     # One at a time
83             while $subdir = $io->next;
84
85           # Print the name and file type for all the contents above:
86           print "$_ is a " . $_->type . "\n"          # Each element of @contents
87             for @contents;                            # is an IO::All object!!
88
89           # Print first line of each file:
90           print $_->getline                           # getline gets one line
91             for io('dir')->all_files;                 # Files only
92
93           # Print names of all files/dirs three directories deep:
94           print "$_\n" for $io->all(3);               # Pass in the depth. Default=1
95
96           # Print names of all files/dirs recursively:
97           print "$_\n" for $io->all(0);               # Zero means all the way down
98           print "$_\n" for $io->All;                  # Capitalized shortcut
99           print "$_\n" for $io->deep->all;            # Another way
100
101           # There are some special file names:
102           print io('-');                              # Print STDIN to STDOUT
103           io('-') > io('-');                          # Do it again
104           io('-') < io('-');                          # Same. Context sensitive.
105           "Bad puppy" > io('=');                      # Message to STDERR
106           $string_file = io('$');                     # Create string based filehandle
107           $temp_file = io('?');                       # Create a temporary file
108
109           # Socket operations:
110           $server = io('localhost:5555')->fork;       # Create a daemon socket
111           $connection = $server->accept;              # Get a connection socket
112           $input < $connection;                       # Get some data from it
113           "Thank you!" > $connection;                 # Thank the caller
114           $connection->close;                         # Hang up
115           io(':6666')->accept->slurp > io->devnull;   # Take a complaint and file it
116
117           # DBM database operations:
118           $dbm = io 'my/database';                    # Create a database object
119           print $dbm->{grocery_list};                 # Hash context makes it a DBM
120           $dbm->{todo} = $new_list;                   # Write to database
121           $dbm->dbm('GDBM_file');                     # Demand specific DBM
122           io('mydb')->mldbm->{env} = \%ENV;           # MLDBM support
123
124           # Tie::File support:
125           $io = io 'file.txt';
126           $io->[42] = 'Line Forty Three';             # Change a line
127           print $io->[@$io / 2];                      # Print middle line
128           @$io = reverse @$io;                        # Reverse lines in a file
129
130           # Stat functions:
131           printf "%s %s %s\n",                        # Print name, uid and size of
132             $_->name, $_->uid, $_->size               # contents of current directory
133               for io('.')->all;
134           print "$_\n" for sort                       # Use mtime method to sort all
135             {$b->mtime <=> $a->mtime}                 # files under current directory
136               io('.')->All_Files;                     # by recent modification time.
137
138           # File::Spec support:
139           $contents < io->catfile(qw(dir file.txt));  # Portable IO operation
140
141           # Miscellaneous:
142           @lines = io('file.txt')->chomp->slurp;      # Chomp as you slurp
143           @chunks =
144             io('file.txt')->separator('xxx')->slurp;  # Use alternnate record sep
145           $binary = io('file.bin')->binary->all;      # Read a binary file
146           io('a-symlink')->readlink->slurp;           # Readlink returns an object
147           print io('foo')->absolute->pathname;        # Print absolute path of foo
148
149           # IO::All External Plugin Methods
150           io("myfile") > io->("ftp://store.org");     # Upload a file using ftp
151           $html < io->http("www.google.com");         # Grab a web page
152           io('mailto:worst@enemy.net')->print($spam); # Email a "friend"
153
154           # This is just the beginning, read on...
155

DESCRIPTION

157       IO::All combines all of the best Perl IO modules into a single nifty
158       object oriented interface to greatly simplify your everyday Perl IO
159       idioms. It exports a single function called "io", which returns a new
160       IO::All object.  And that object can do it all!
161
162       The IO::All object is a proxy for IO::File, IO::Dir, IO::Socket,
163       Tie::File, File::Spec, File::Path, File::MimeInfo and
164       File::ReadBackwards; as well as all the DBM and MLDBM modules. You can
165       use most of the methods found in these classes and in IO::Handle (which
166       they inherit from). IO::All adds dozens of other helpful idiomatic
167       methods including file stat and manipulation functions.
168
169       IO::All is pluggable, and modules like IO::All::LWP and IO::All::Mailto
170       add even more functionality. Optionally, every IO::All object can be
171       tied to itself. This means that you can use most perl IO builtins on
172       it: readline, "<>", getc, print, printf, syswrite, sysread, close.
173
174       The distinguishing magic of IO::All is that it will automatically open
175       (and close) files, directories, sockets and other IO things for you.
176       You never need to specify the mode ("<", ">>", etc), since it is
177       determined by the usage context. That means you can replace this:
178
179           open STUFF, '<', './mystuff'
180             or die "Can't open './mystuff' for input:\n$!";
181           local $/;
182           my $stuff = <STUFF>;
183           close STUFF;
184
185       with this:
186
187           my $stuff < io './mystuff';
188
189       And that is a good thing!
190

USAGE

192       Normally just say:
193
194           use IO::All;
195
196       and IO::All will export a single function called "io", which constructs
197       all IO objects.
198
199   Note on "io"
200       The "io" function is a magic constructor. It is easy to use and will
201       usually do the right thing, but can also blow up easily.
202
203       It takes a single optional argument and determines what type of IO::All
204       subclass object to return. With no arguments it returns an "IO::All"
205       object, which has no I/O methods, but has methods to construct subclass
206       objects like "IO::All::File".
207
208       In other words, these 2 statements are usually the same:
209
210           $content = io('file.txt')->all;
211           $content = io->file('file.txt')->all;
212
213       Use the first form when you are demonstrating your Perl virtues of
214       laziness and impatience, and use the second form when your job is on
215       the line.
216

METHOD ROLE CALL

218       Here is an alphabetical list of all the public methods that you can
219       call on an IO::All object.
220
221       "abs2rel", "absolute", "accept", "All", "all", "All_Dirs", "all_dirs",
222       "All_Files", "all_files", "All_Links", "all_links", "append",
223       "appendf", "appendln", "assert", "atime", "autoclose", "autoflush",
224       "backwards", "bcc", "binary", "binmode", "blksize", "blocks",
225       "block_size", "buffer", "canonpath", "case_tolerant", "catdir",
226       "catfile", "catpath", "cc", "chdir", "chomp", "clear", "close",
227       "confess", "content", "copy", "ctime", "curdir", "dbm", "deep",
228       "device", "device_id", "devnull", "dir", "domain", "empty", "ext",
229       "encoding", "eof", "errors", "file", "filename", "fileno", "filepath",
230       "filter", "fork", "from", "ftp", "get", "getc", "getline", "getlines",
231       "gid", "glob", "handle", "head", "http", "https", "inode", "io_handle",
232       "is_absolute", "is_dir", "is_dbm", "is_executable", "is_file",
233       "is_link", "is_mldbm", "is_open", "is_pipe", "is_readable",
234       "is_socket", "is_stdio", "is_string", "is_temp", "is_writable", "join",
235       "length", "link", "lock", "mailer", "mailto", "mimetype", "mkdir",
236       "mkpath", "mldbm", "mode", "modes", "mtime", "name", "new", "next",
237       "nlink", "open", "os" "password", "path", "pathname", "perms", "pipe",
238       "port", "print", "printf", "println", "put", "rdonly", "rdwr", "read",
239       "readdir", "readlink", "recv", "rel2abs", "relative", "rename",
240       "request", "response", "rmdir", "rmtree", "rootdir", "scalar", "seek",
241       "send", "separator", "shutdown", "size", "slurp", "socket", "sort",
242       "splitdir", "splitpath", "stat", "stdio", "stderr", "stdin", "stdout",
243       "string", "string_ref", "subject", "sysread", "syswrite", "tail",
244       "tell", "temp", "tie", "tmpdir", "to", "touch", "truncate", "type",
245       "user", "uid", "unlink", "unlock", "updir", "uri", "utf8", "utime" and
246       "write".
247
248       Each method is documented further below.
249

OPERATOR OVERLOADING

251       IO::All objects overload a small set of Perl operators to great effect.
252       The overloads are limited to "<", "<<", ">", ">>", dereferencing
253       operations, and stringification.
254
255       Even though relatively few operations are overloaded, there is actually
256       a huge matrix of possibilities for magic. That's because the
257       overloading is sensitive to the types, position and context of the
258       arguments, and an IO::All object can be one of many types.
259
260       The most important overload to become familiar with is stringification.
261       IO::All objects stringify to their file or directory name. Here we
262       print the contents of the current directory:
263
264           perl -MIO::All -le 'print for io(".")->all'
265
266       is the same as:
267
268           perl -MIO::All -le 'print $_->name for io(".")->all'
269
270       Stringification is important because it allows IO::All operations to
271       return objects when they might otherwise return file names. Then the
272       recipient can use the result either as an object or a string.
273
274       ">" and "<" move data between objects in the direction pointed to by
275       the operator.
276
277           $content1 < io('file1');
278           $content1 > io('file2');
279           io('file2') > $content3;
280           io('file3') < $content3;
281           io('file3') > io('file4');
282           io('file5') < io('file4');
283
284       ">>" and "<<" do the same thing except the recipient string or file is
285       appended to.
286
287       An IO::All file used as an array reference becomes tied using
288       Tie::File:
289
290           $file = io "file";
291           # Print last line of file
292           print $file->[-1];
293           # Insert new line in middle of file
294           $file->[$#$file / 2] = 'New line';
295
296       An IO::All file used as a hash reference becomes tied to a DBM class:
297
298           io('mydbm')->{ingy} = 'YAML';
299
300       An IO::All directory used as an array reference, will expose each file
301       or subdirectory as an element of the array.
302
303           print "$_\n" for @{io 'dir'};
304
305       IO::All directories used as hash references have file names as keys,
306       and IO::All objects as values:
307
308           print io('dir')->{'foo.txt'}->slurp;
309
310       Files used as scalar references get slurped:
311
312           print ${io('dir')->{'foo.txt'}};
313
314       Not all combinations of operations and object types are supported. Some
315       just haven't been added yet, and some just don't make sense. If you use
316       an invalid combination, an error will be thrown.
317

COOKBOOK

319       This section describes some various things that you can easily cook up
320       with IO::All.
321
322   File Locking
323       IO::All makes it very easy to lock files. Just use the "lock" method.
324       Here's a standalone program that demonstrates locking for both write
325       and read:
326
327           use IO::All;
328           my $io1 = io('myfile')->lock;
329           $io1->println('line 1');
330
331           fork or do {
332             my $io2 = io('myfile')->lock;
333             print $io2->slurp;
334             exit;
335           };
336
337           sleep 1;
338           $io1->println('line 2');
339           $io1->println('line 3');
340           $io1->unlock;
341
342       There are a lot of subtle things going on here. An exclusive lock is
343       issued for $io1 on the first "println". That's because the file isn't
344       actually opened until the first IO operation.
345
346       When the child process tries to read the file using $io2, there is a
347       shared lock put on it. Since $io1 has the exclusive lock, the slurp
348       blocks.
349
350       The parent process sleeps just to make sure the child process gets a
351       chance.  The parent needs to call "unlock" or "close" to release the
352       lock. If all goes well the child will print 3 lines.
353
354   In-place Editing
355       Because an IO::All object can be used as an array reference, operations
356       on arrays are supported transparently (using Tie::File) so a file can
357       be modified in the same way you would modify an array.
358
359           > cat > x.txt
360           The sexy saxophone,
361
362           got the axe.
363           ^d
364
365           > perl -MIO::All -e 'map { s/x/X/g; $_ } @{ io(shift) }' x.txt
366           > cat x.txt
367           The seXy saXophone,
368
369           got the aXe.
370
371        This one liner uses shift() to grab the file from STDIN and create an io
372        object that is dereferenced using @{ } and fed to map() like any perl array
373        reference.
374
375   Round Robin
376       This simple example will read lines from a file forever. When the last
377       line is read, it will reopen the file and read the first one again.
378
379           my $io = io 'file1.txt';
380           $io->autoclose(1);
381           while (my $line = $io->getline || $io->getline) {
382             print $line;
383           }
384
385   Reading Backwards
386       If you call the "backwards" method on an IO::All object, the "getline"
387       and "getlines" will work in reverse. They will read the lines in the
388       file from the end to the beginning.
389
390           my @reversed;
391           my $io = io('file1.txt');
392           $io->backwards;
393           while (my $line = $io->getline) {
394             push @reversed, $line;
395           }
396
397       or more simply:
398
399           my @reversed = io('file1.txt')->backwards->getlines;
400
401       The "backwards" method returns the IO::All object so that you can chain
402       the calls.
403
404       NOTE: This operation requires that you have the File::ReadBackwards
405       module
406             installed.
407
408   Client/Server Sockets
409       IO::All makes it really easy to write a forking socket server and a
410       client to talk to it.
411
412       In this example, a server will return 3 lines of text, to every client
413       that calls it. Here is the server code:
414
415           use IO::All;
416
417           my $socket = io(':12345')->fork->accept;
418           $socket->print($_) while <DATA>;
419           $socket->close;
420
421           __DATA__
422           On your mark,
423           Get set,
424           Go!
425
426       Here is the client code:
427
428           use IO::All;
429
430           my $io = io('localhost:12345');
431           print while $_ = $io->getline;
432
433       You can run the server once, and then run the client repeatedly (in
434       another terminal window). It should print the 3 data lines each time.
435
436       Note that it is important to close the socket if the server is forking,
437       or else the socket won't go out of scope and close.
438
439   A Tiny Web Server
440       Here is how you could write a simplistic web server that works with
441       static and dynamic pages:
442
443           perl -MIO::All -e 'io(":8080")->fork->accept->(sub { $_[0] < io(-x $1 ? "./$1 |" : $1) if /^GET \/(.*) / })'
444
445       There is are a lot of subtle things going on here. First we accept a
446       socket and fork the server. Then we overload the new socket as a code
447       ref. This code ref takes one argument, another code ref, which is used
448       as a callback.
449
450       The callback is called once for every line read on the socket. The line
451       is put into $_ and the socket itself is passed in to the callback.
452
453       Our callback is scanning the line in $_ for an HTTP GET request. If one
454       is found it parses the file name into $1. Then we use $1 to create an
455       new IO::All file object... with a twist. If the file is executable
456       ("-x"), then we create a piped command as our IO::All object. This
457       somewhat approximates CGI support.
458
459       Whatever the resulting object is, we direct the contents back at our
460       socket which is in $_[0]. Pretty simple, eh?
461
462   DBM Files
463       IO::All file objects used as a hash reference, treat the file as a DBM
464       tied to a hash. Here I write my DB record to STDERR:
465
466           io("names.db")->{ingy} > io('=');
467
468       Since their are several DBM formats available in Perl, IO::All picks
469       the first one of these that is installed on your system:
470
471           DB_File GDBM_File NDBM_File ODBM_File SDBM_File
472
473       You can override which DBM you want for each IO::All object:
474
475           my @keys = keys %{io('mydbm')->dbm('SDBM_File')};
476
477   File Subclassing
478       Subclassing is easy with IO::All. Just create a new module and use
479       IO::All as the base class, like this:
480
481           package NewModule;
482           use IO::All -base;
483
484       You need to do it this way so that IO::All will export the "io"
485       function.  Here is a simple recipe for subclassing:
486
487       IO::Dumper inherits everything from IO::All and adds an extra method
488       called "dump", which will dump a data structure to the file we specify
489       in the "io" function. Since it needs Data::Dumper to do the dumping, we
490       override the "open" method to "require Data::Dumper" and then pass
491       control to the real "open".
492
493       First the code using the module:
494
495           use IO::Dumper;
496
497           io('./mydump')->dump($hash);
498
499       And next the IO::Dumper module itself:
500
501           package IO::Dumper;
502           use IO::All -base;
503           use Data::Dumper;
504
505           sub dump {
506             my $self = shift;
507             Dumper(@_) > $self;
508           }
509
510           1;
511
512   Inline Subclassing
513       This recipe does the same thing as the previous one, but without
514       needing to write a separate module. The only real difference is the
515       first line. Since you don't "use" IO::Dumper, you need to still call
516       its "import" method manually.
517
518           IO::Dumper->import;
519           io('./mydump')->dump($hash);
520
521           package IO::Dumper;
522           use IO::All -base;
523           use Data::Dumper;
524
525           sub dump {
526             my $self = shift;
527             Dumper(@_) > $self;
528           }
529

THE IO::ALL METHODS

531       This section gives a full description of all of the methods that you
532       can call on IO::All objects. The methods have been grouped into
533       subsections based on object construction, option settings,
534       configuration, action methods and support for specific modules.
535
536   Object Construction and Initialization Methods
537       new There are three ways to create a new IO::All object. The first is
538           with the special function "io" which really just calls
539           "IO::All->new". The second is by calling "new" as a class method.
540           The third is calling "new" as an object instance method. In this
541           final case, the new objects attributes are copied from the instance
542           object.
543
544               io(file-descriptor);
545               IO::All->new(file-descriptor);
546               $io->new(file-descriptor);
547
548           All three forms take a single argument, a file descriptor. A file
549           descriptor can be any of the following:
550
551               - A file name
552               - A file handle
553               - A directory name
554               - A directory handle
555               - A typeglob reference
556               - A piped shell command. eg '| ls -al'
557               - A socket domain/port.  eg 'perl.com:5678'
558               - '-' means STDIN or STDOUT (depending on usage)
559               - '=' means STDERR
560               - '$' means an in memory filehandle object
561               - '?' means a temporary file
562               - A URI including: http, https, ftp and mailto
563               - An IO::All object
564
565           If you provide an IO::All object, you will simply get that same
566           object returned from the constructor.
567
568           If no file descriptor is provided, an object will still be created,
569           but it must be defined by one of the following methods before it
570           can be used for I/O:
571
572       file
573               io->file("path/to/my/file.txt");
574
575           Using the "file" method sets the type of the object to file and
576           sets the pathname of the file if provided.
577
578           It might be important to use this method if you had a file whose
579           name was '- ', or if the name might otherwise be confused with a
580           directory or a socket.  In this case, either of these statements
581           would work the same:
582
583               my $file = io('-')->file;
584               my $file = io->file('-');
585
586       dir
587               io->dir($dir_name);
588
589           Make the object be of type directory.
590
591       socket
592               io->socket("${domain}:${port}");
593
594           Make the object be of type socket.
595
596       link
597               io->link($link_name);
598
599           Make the object be of type link.
600
601       pipe
602               io->pipe($pipe_command);
603
604           Make the object be of type pipe. The following three statements are
605           equivalent:
606
607               my $io = io('ls -l |');
608               my $io = io('ls -l')->pipe;
609               my $io = io->pipe('ls -l');
610
611       dbm This method takes the names of zero or more DBM modules. The first
612           one that is available is used to process the dbm file.
613
614               io('mydbm')->dbm('NDBM_File', 'SDBM_File')->{author} = 'ingy';
615
616           If no module names are provided, the first available of the
617           following is used:
618
619               DB_File GDBM_File NDBM_File ODBM_File SDBM_File
620
621       mldbm
622           Similar to the "dbm" method, except create a Multi Level DBM object
623           using the MLDBM module.
624
625           This method takes the names of zero or more DBM modules and an
626           optional serialization module. The first DBM module that is
627           available is used to process the MLDBM file. The serialization
628           module can be Data::Dumper, Storable or FreezeThaw.
629
630               io('mymldbm')->mldbm('GDBM_File', 'Storable')->{author} =
631                 {nickname => 'ingy'};
632
633       string
634           Make the object be an in memory filehandle. These are equivalent:
635
636               my $io = io('$');
637               my $io = io->string;
638
639       temp
640           Make the object represent a temporary file. It will automatically
641           be open for both read and write.
642
643       stdio
644           Make the object represent either STDIN or STDOUT depending on how
645           it is used subsequently. These are equivalent:
646
647               my $io = io('-');
648               my $io = io->stdin;
649
650       stdin
651           Make the object represent STDIN.
652
653       stdout
654           Make the object represent STDOUT.
655
656       stderr
657           Make the object represent STDERR.
658
659       handle
660               io->handle($io_handle);
661
662           Forces the object to be created from an pre-existing IO handle. You
663           can chain calls together to indicate the type of handle:
664
665               my $file_object = io->file->handle($file_handle);
666               my $dir_object = io->dir->handle($dir_handle);
667
668       http
669           Make the object represent an HTTP URI. Requires IO-All-LWP.
670
671       https
672           Make the object represent an HTTPS URI. Requires IO-All-LWP.
673
674       ftp Make the object represent an FTP URI. Requires IO-All-LWP.
675
676       mailto
677           Make the object represent a "mailto:" URI. Requires IO-All-Mailto.
678
679       If you need to use the same options to create a lot of objects, and
680       don't want to duplicate the code, just create a dummy object with the
681       options you want, and use that object to spawn other objects.
682
683           my $lt = io->lock->tie;
684           ...
685           my $io1 = $lt->new('file1');
686           my $io2 = $lt->new('file2');
687
688       Since the new method copies attributes from the calling object, both
689       $io1 and $io2 will be locked and tied.
690
691   Option Setting Methods
692       The following methods don't do any actual IO, but they specify options
693       about how the IO should be done.
694
695       Each option can take a single argument of 0 or 1. If no argument is
696       given, the value 1 is assumed. Passing 0 turns the option off.
697
698       All of these options return the object reference that was used to
699       invoke them.  This is so that the option methods can be chained
700       together. For example:
701
702           my $io = io('path/file')->tie->assert->chomp->lock;
703
704       absolute
705           Indicates that the "pathname" for the object should be made
706           absolute.
707
708               # Print the full path of the current working directory
709               # (like pwd).
710
711               use IO::All;
712
713               print io->curdir->absolute;
714
715       assert
716           This method ensures that the path for a file or directory actually
717           exists before the file is open. If the path does not exist, it is
718           created.
719
720           For example, here is a program called "create-cat-to" that outputs
721           to a file that it creates.
722
723               #!/usr/bin/perl
724
725               # create-cat-to.pl
726               # cat to a file that can be created.
727
728               use strict;
729               use warnings;
730
731               use IO::All;
732
733               my $filename = shift(@ARGV);
734
735               # Create a file called $filename, including all leading components.
736               io('-') > io->file($filename)->assert;
737
738           Here's an example use of it:
739
740               $ ls -l
741               total 0
742               $ echo "Hello World" | create-cat-to one/two/three/four.txt
743               $ ls -l
744               total 4
745               drwxr-xr-x 3 shlomif shlomif 4096 2010-10-14 18:03 one/
746               $ cat one/two/three/four.txt
747               Hello World
748               $
749
750       autoclose
751           By default, IO::All will close an object opened for input when EOF
752           is reached.  By closing the handle early, one can immediately do
753           other operations on the object without first having to close it.
754
755           This option is on by default, so if you don't want this behaviour,
756           say so like this:
757
758               $io->autoclose(0);
759
760           The object will then be closed when $io goes out of scope, or you
761           manually call "$io->close".
762
763       autoflush
764           Proxy for IO::Handle::autoflush
765
766       backwards
767           Sets the object to 'backwards' mode. All subsequent "getline"
768           operations will read backwards from the end of the file.
769
770           Requires the File::ReadBackwards CPAN module.
771
772       binary
773           Adds ":raw" to the list of PerlIO layers applied after "open", and
774           applies it immediately on an open handle.
775
776       chdir
777           chdir() to the pathname of a directory object. When object goes out
778           of scope, chdir back to starting directory.
779
780       chomp
781           Indicates that all operations that read lines should chomp the
782           lines. If the "separator" method has been called, chomp will remove
783           that value from the end of each record.
784
785           Note that "chomp" may cause the following idiom to halt prematurely
786           (e.g., if "separator" is "\n" (the default) and "chomp" is in
787           effect, then this command will stop reading at the first blank
788           line):
789
790               while ( my $line = $io->getline ) {...}
791
792           Try the following instead:
793
794               while ( defined(my $line = $io->getline) ) {...}
795
796       confess
797           Errors should be reported with the very detailed Carp::confess
798           function.
799
800       deep
801           Indicates that calls to the "all" family of methods should search
802           directories as deep as possible.
803
804       fork
805           Indicates that the process should automatically be forked inside
806           the "accept" socket method.
807
808       lock
809           Indicate that operations on an object should be locked using flock.
810
811       rdonly
812           This option indicates that certain operations like DBM and
813           Tie::File access should be done in read-only mode.
814
815       rdwr
816           This option indicates that DBM and MLDBM files should be opened in
817           read/write mode.
818
819       relative
820           Indicates that the "pathname" for the object should be made
821           relative. If passed an argument, path will be made relative to
822           passed argument.
823
824       sort
825           Indicates whether objects returned from one of the "all" methods
826           will be in sorted order by name. True by default.
827
828       tie Indicate that the object should be tied to itself, thus allowing it
829           to be used as a filehandle in any of Perl's builtin IO operations.
830
831               my $io = io('foo')->tie;
832               @lines = <$io>;
833
834       utf8
835           Adds ":encoding(UTF-8)" to the list of PerlIO layers applied after
836           "open", and applies it immediately on an open handle.
837
838   Configuration Methods
839       The following methods don't do any actual I/O, but they set specific
840       values to configure the IO::All object.
841
842       If these methods are passed no argument, they will return their current
843       value.  If arguments are passed they will be used to set the current
844       value, and the object reference will be returned for potential method
845       chaining.
846
847       bcc Set the Bcc field for a mailto object.
848
849       binmode
850           Adds the specified layer to the list of PerlIO layers applied after
851           "open", and applies it immediately on an open handle. Does a bare
852           "binmode" when called without argument.
853
854       block_size
855           The default length to be used for "read" and "sysread" calls.
856           Defaults to 1024.
857
858       buffer
859           Returns a reference to the internal buffer, which is a scalar. You
860           can use this method to set the buffer to a scalar of your choice.
861           (You can just pass in the scalar, rather than a reference to it.)
862
863           This is the buffer that "read" and "write" will use by default.
864
865           You can easily have IO::All objects use the same buffer:
866
867               my $input = io('abc');
868               my $output = io('xyz');
869               my $buffer;
870               $output->buffer($input->buffer($buffer));
871               $output->write while $input->read;
872
873       cc  Set the Cc field for a mailto object.
874
875       content
876           Get or set the content for an LWP operation manually.
877
878       domain
879           Set the domain name or ip address that a socket should use.
880
881       encoding
882           Adds the specified encoding to the list of PerlIO layers applied
883           after "open", and applies it immediately on an open handle.
884           Requires an argument.
885
886       errors
887           Use this to set a subroutine reference that gets called when an
888           internal error is thrown.
889
890       filter
891           Use this to set a subroutine reference that will be used to grep
892           which objects get returned on a call to one of the "all" methods.
893           For example:
894
895               my @odd = io->curdir->filter(sub {$_->size % 2})->All_Files;
896
897           @odd will contain all the files under the current directory whose
898           size is an odd number of bytes.
899
900       from
901           Indicate the sender for a mailto object.
902
903       mailer
904           Set the mailer program for a mailto transaction. Defaults to
905           'sendmail'.
906
907       mode
908           Set the mode for which the file should be opened. Examples:
909
910               $io->mode('>>')->open;
911               $io->mode(O_RDONLY);
912
913               my $log_appender = io->file('/var/log/my-application.log')
914                                    ->mode('>>')->open();
915
916               $log_appender->print("Stardate 5987.6: Mission accomplished.");
917
918       name
919           Set or get the name of the file or directory represented by the
920           IO::All object.
921
922       password
923           Set the password for an LWP transaction.
924
925       perms
926           Sets the permissions to be used if the file/directory needs to be
927           created.
928
929       port
930           Set the port number that a socket should use.
931
932       request
933           Manually specify the request object for an LWP transaction.
934
935       response
936           Returns the resulting response object from an LWP transaction.
937
938       separator
939           Sets the record (line) separator to whatever value you pass it.
940           Default is "\n". Affects the chomp setting too.
941
942       string_ref
943           Returns a reference to the internal string that is acting like a
944           file.
945
946       subject
947           Set the subject for a mailto transaction.
948
949       to  Set the recipient address for a mailto request.
950
951       uri Direct access to the URI used in LWP transactions.
952
953       user
954           Set the user name for an LWP transaction.
955
956   IO Action Methods
957       These are the methods that actually perform I/O operations on an
958       IO::All object. The stat methods and the File::Spec methods are
959       documented in separate sections below.
960
961       accept
962           For sockets. Opens a server socket (LISTEN => 1, REUSE => 1).
963           Returns an IO::All socket object that you are listening on.
964
965           If the "fork" method was called on the object, the process will
966           automatically be forked for every connection.
967
968       all Read all contents into a single string.
969
970               compare(io('file1')->all, io('file2')->all);
971
972       all (For directories)
973           Returns a list of IO::All objects for all files and subdirectories
974           in a directory.
975
976           '.' and '..' are excluded.
977
978           Takes an optional argument telling how many directories deep to
979           search. The default is 1. Zero (0) means search as deep as
980           possible.
981
982           The filter method can be used to limit the results.
983
984           The items returned are sorted by name unless "->sort(0)" is used.
985
986       All Same as all(0).
987
988       all_dirs
989           Same as "all", but only return directories.
990
991       All_Dirs
992           Same as all_dirs(0).
993
994       all_files
995           Same as "all", but only return files.
996
997       All_Files
998           Same as all_files(0).
999
1000       all_links
1001           Same as "all", but only return links.
1002
1003       All_Links
1004           Same as all_links(0).
1005
1006       append
1007           Same as print, but sets the file mode to '>>'.
1008
1009       appendf
1010           Same as printf, but sets the file mode to '>>'.
1011
1012       appendln
1013           Same as println, but sets the file mode to '>>'.
1014
1015       clear
1016           Clear the internal buffer. This method is called by "write" after
1017           it writes the buffer. Returns the object reference for chaining.
1018
1019       close
1020           Close will basically unopen the object, which has different
1021           meanings for different objects. For files and directories it will
1022           close and release the handle. For sockets it calls shutdown. For
1023           tied things it unties them, and it unlocks locked things.
1024
1025       copy
1026           Copies the object to the path passed. Works on both files and
1027           directories, but directories require "File::Copy::Recursive" to be
1028           installed.
1029
1030       empty
1031           Returns true if a file exists but has no size, or if a directory
1032           exists but has no contents.
1033
1034       eof Proxy for IO::Handle::eof
1035
1036       ext Returns the extension of the file. Can also be spelled as
1037           "extension"
1038
1039       exists
1040           Returns whether or not the file or directory exists.
1041
1042       filename
1043           Return the name portion of the file path in the object. For
1044           example:
1045
1046               io('my/path/file.txt')->filename;
1047
1048           would return "file.txt".
1049
1050       fileno
1051           Proxy for IO::Handle::fileno
1052
1053       filepath
1054           Return the path portion of the file path in the object. For
1055           example:
1056
1057               io('my/path/file.txt')->filepath;
1058
1059           would return "my/path".
1060
1061       get Perform an LWP GET request manually.
1062
1063       getc
1064           Proxy for IO::Handle::getc
1065
1066       getline
1067           Calls IO::File::getline. You can pass in an optional record
1068           separator.
1069
1070       getlines
1071           Calls IO::File::getlines. You can pass in an optional record
1072           separator.
1073
1074       glob
1075           Creates IO::All objects for the files matching the glob in the
1076           IO::All::Dir.  For example:
1077
1078               io->dir($ENV{HOME})->glob('*.txt')
1079
1080       head
1081           Return the first 10 lines of a file. Takes an optional argument
1082           which is the number of lines to return. Works as expected in list
1083           and scalar context. Is subject to the current line separator.
1084
1085       io_handle
1086           Direct access to the actual IO::Handle object being used on an
1087           opened IO::All object.
1088
1089       is_dir
1090           Returns boolean telling whether or not the IO::All object
1091           represents a directory.
1092
1093       is_executable
1094           Returns true if file or directory is executable.
1095
1096       is_dbm
1097           Returns boolean telling whether or not the IO::All object
1098           represents a dbm file.
1099
1100       is_file
1101           Returns boolean telling whether or not the IO::All object
1102           represents a file.
1103
1104       is_link
1105           Returns boolean telling whether or not the IO::All object
1106           represents a symlink.
1107
1108       is_mldbm
1109           Returns boolean telling whether or not the IO::All object
1110           represents a mldbm file.
1111
1112       is_open
1113           Indicates whether the IO::All is currently open for input/output.
1114
1115       is_pipe
1116           Returns boolean telling whether or not the IO::All object
1117           represents a pipe operation.
1118
1119       is_readable
1120           Returns true if file or directory is readable.
1121
1122       is_socket
1123           Returns boolean telling whether or not the IO::All object
1124           represents a socket.
1125
1126       is_stdio
1127           Returns boolean telling whether or not the IO::All object
1128           represents a STDIO file handle.
1129
1130       is_string
1131           Returns boolean telling whether or not the IO::All object
1132           represents an in memory filehandle.
1133
1134       is_temp
1135           Returns boolean telling whether or not the IO::All object
1136           represents a temporary file.
1137
1138       is_writable
1139           Returns true if file or directory is writable. Can also be spelled
1140           as "is_writeable".
1141
1142       length
1143           Return the length of the internal buffer.
1144
1145       mimetype
1146           Return the mimetype of the file.
1147
1148           Requires a working installation of the File::MimeInfo CPAN module.
1149
1150       mkdir
1151           Create the directory represented by the object.
1152
1153       mkpath
1154           Create the directory represented by the object, when the path
1155           contains more than one directory that doesn't exist. Proxy for
1156           File::Path::mkpath.
1157
1158       next
1159           For a directory, this will return a new IO::All object for each
1160           file or subdirectory in the directory. Return undef on EOD.
1161
1162       open
1163           Open the IO::All object. Takes two optional arguments "mode" and
1164           "perms", which can also be set ahead of time using the "mode" and
1165           "perms" methods.
1166
1167           NOTE: Normally you won't need to call open (or mode/perms), since
1168           this happens
1169                 automatically for most operations.
1170
1171       os  Change the object's os representation. Valid options are: "win32",
1172           "unix", "vms", "mac", "os2".
1173
1174       pathname
1175           Return the absolute or relative pathname for a file or directory,
1176           depending on whether object is in "absolute" or "relative" mode.
1177
1178       print
1179           Proxy for IO::Handle::print
1180
1181       printf
1182           Proxy for IO::Handle::printf
1183
1184       println
1185           Same as print, but adds newline to each argument unless it already
1186           ends with one.
1187
1188       put Perform an LWP PUT request manually.
1189
1190       read
1191           This method varies depending on its context. Read carefully (no pun
1192           intended).
1193
1194           For a file, this will proxy IO::File::read. This means you must
1195           pass it a buffer, a length to read, and optionally a buffer offset
1196           for where to put the data that is read. The function returns the
1197           length actually read (which is zero at EOF).
1198
1199           If you don't pass any arguments for a file, IO::All will use its
1200           own internal buffer, a default length, and the offset will always
1201           point at the end of the buffer. The buffer can be accessed with the
1202           "buffer" method. The length can be set with the "block_size"
1203           method. The default length is 1024 bytes. The "clear" method can be
1204           called to clear the buffer.
1205
1206           For a directory, this will proxy IO::Dir::read.
1207
1208       readdir
1209           Similar to the Perl "readdir" builtin. In scalar context, return
1210           the next directory entry (ie file or directory name), or undef on
1211           end of directory. In list context, return all directory entries.
1212
1213           Note that "readdir" does not return the special "." and ".."
1214           entries.
1215
1216       readline
1217           Same as "getline".
1218
1219       readlink
1220           Calls Perl's readlink function on the link represented by the
1221           object.  Instead of returning the file path, it returns a new
1222           IO::All object using the file path.
1223
1224       recv
1225           Proxy for IO::Socket::recv
1226
1227       rename
1228               my $new = $io->rename('new-name');
1229
1230           Calls Perl's rename function and returns an IO::All object for the
1231           renamed file. Returns false if the rename failed.
1232
1233       rewind
1234           Proxy for IO::Dir::rewind
1235
1236       rmdir
1237           Delete the directory represented by the IO::All object.
1238
1239       rmtree
1240           Delete the directory represented by the IO::All object and all the
1241           files and directories beneath it. Proxy for File::Path::rmtree.
1242
1243       scalar
1244           Deprecated. Same as "all()".
1245
1246       seek
1247           Proxy for IO::Handle::seek. If you use seek on an unopened file, it
1248           will be opened for both read and write.
1249
1250       send
1251           Proxy for IO::Socket::send
1252
1253       shutdown
1254           Proxy for IO::Socket::shutdown
1255
1256       slurp
1257           Read all file content in one operation. Returns the file content as
1258           a string.  In list context returns every line in the file.
1259
1260       stat
1261           Proxy for IO::Handle::stat
1262
1263       sysread
1264           Proxy for IO::Handle::sysread
1265
1266       syswrite
1267           Proxy for IO::Handle::syswrite
1268
1269       tail
1270           Return the last 10 lines of a file. Takes an optional argument
1271           which is the number of lines to return. Works as expected in list
1272           and scalar context. Is subject to the current line separator.
1273
1274       tell
1275           Proxy for IO::Handle::tell
1276
1277       throw
1278           This is an internal method that gets called whenever there is an
1279           error. It could be useful to override it in a subclass, to provide
1280           more control in error handling.
1281
1282       touch
1283           Update the atime and mtime values for a file or directory. Creates
1284           an empty file if the file does not exist.
1285
1286       truncate
1287           Proxy for IO::Handle::truncate
1288
1289       type
1290           Returns a string indicated the type of io object. Possible values
1291           are:
1292
1293               file
1294               dir
1295               link
1296               socket
1297               string
1298               pipe
1299
1300           Returns undef if type is not determinable.
1301
1302       unlink
1303           Unlink (delete) the file represented by the IO::All object.
1304
1305           NOTE: You can unlink a file after it is open, and continue using it
1306           until it
1307                 is closed.
1308
1309       unlock
1310           Release a lock from an object that used the "lock" method.
1311
1312       utime
1313           Proxy for the utime Perl function.
1314
1315       write
1316           Opposite of "read" for file operations only.
1317
1318           NOTE: When used with the automatic internal buffer, "write" will
1319           clear the
1320                 buffer after writing it.
1321
1322   Stat Methods
1323       This methods get individual values from a stat call on the file,
1324       directory or handle represented by the IO::All object.
1325
1326       atime
1327           Last access time in seconds since the epoch
1328
1329       blksize
1330           Preferred block size for file system I/O
1331
1332       blocks
1333           Actual number of blocks allocated
1334
1335       ctime
1336           Inode change time in seconds since the epoch
1337
1338       device
1339           Device number of filesystem
1340
1341       device_id
1342           Device identifier for special files only
1343
1344       gid Numeric group id of file's owner
1345
1346       inode
1347           Inode number
1348
1349       modes
1350           File mode - type and permissions
1351
1352       mtime
1353           Last modify time in seconds since the epoch
1354
1355       nlink
1356           Number of hard links to the file
1357
1358       size
1359           Total size of file in bytes
1360
1361       uid Numeric user id of file's owner
1362
1363   File::Spec Methods
1364       These methods are all adaptations from File::Spec. Each method actually
1365       does call the matching File::Spec method, but the arguments and return
1366       values differ slightly. Instead of being file and directory names, they
1367       are IO::All objects. Since IO::All objects stringify to their names,
1368       you can generally use the methods just like File::Spec.
1369
1370       abs2rel
1371           Returns the relative path for the absolute path in the IO::All
1372           object. Can take an optional argument indicating the base path.
1373
1374       canonpath
1375           Returns the canonical path for the IO::All object. The canonical
1376           path is the fully resolved path if the file exists, so any symlinks
1377           will be resolved.
1378
1379       case_tolerant
1380           Returns 0 or 1 indicating whether the file system is case tolerant.
1381           Since an active IO::All object is not needed for this function, you
1382           can code it like:
1383
1384               IO::All->case_tolerant;
1385
1386           or more simply:
1387
1388               io->case_tolerant;
1389
1390       catdir
1391           Concatenate the directory components together, and return a new
1392           IO::All object representing the resulting directory.
1393
1394       catfile
1395           Concatenate the directory and file components together, and return
1396           a new IO::All object representing the resulting file.
1397
1398               my $contents = io->catfile(qw(dir subdir file))->slurp;
1399
1400           This is a very portable way to read "dir/subdir/file".
1401
1402       catpath
1403           Concatenate the volume, directory and file components together, and
1404           return a new IO::All object representing the resulting file.
1405
1406       curdir
1407           Returns an IO::All object representing the current directory.
1408
1409       devnull
1410           Returns an IO::All object representing the "/dev/null" file.
1411
1412       is_absolute
1413           Returns 0 or 1 indicating whether the "name" field of the IO::All
1414           object is an absolute path.
1415
1416       join
1417           Same as "catfile".
1418
1419       path
1420           Returns a list of IO::All directory objects for each directory in
1421           your path.
1422
1423       rel2abs
1424           Returns the absolute path for the relative path in the IO::All
1425           object. Can take an optional argument indicating the base path.
1426
1427       rootdir
1428           Returns an IO::All object representing the root directory on your
1429           file system.
1430
1431       splitdir
1432           Returns a list of the directory components of a path in an IO::All
1433           object.
1434
1435       splitpath
1436           Returns a volume directory and file component of a path in an
1437           IO::All object.
1438
1439       tmpdir
1440           Returns an IO::All object representing a temporary directory on
1441           your file system.
1442
1443       updir
1444           Returns an IO::All object representing the current parent
1445           directory.
1446

OPERATIONAL NOTES

1448       Reblessing
1449           Each IO::All object gets reblessed into an IO::All::* object as
1450           soon as IO::All can determine what type of object it should be.
1451           Sometimes it gets reblessed more than once:
1452
1453               my $io = io('mydbm.db');
1454               $io->dbm('DB_File');
1455               $io->{foo} = 'bar';
1456
1457           In the first statement, $io has a reference value of
1458           'IO::All::File', if "mydbm.db" exists. In the second statement, the
1459           object is reblessed into class 'IO::All::DBM'.
1460
1461       Auto-Open
1462           An IO::All object will automatically be opened as soon as there is
1463           enough contextual information to know what type of object it is,
1464           and what mode it should be opened for. This is usually when the
1465           first read or write operation is invoked but might be sooner.
1466
1467       Auto-Mode
1468           The mode for an object to be opened with is determined
1469           heuristically unless specified explicitly.
1470
1471       Auto-Close
1472           For input, IO::All objects will automatically be closed after EOF
1473           (or EOD).  For output, the object closes when it goes out of scope.
1474
1475           To keep input objects from closing at EOF, do this:
1476
1477               $io->autoclose(0);
1478
1479       Explicit open and close
1480           You can always call "open" and "close" explicitly, if you need that
1481           level of control. To test if an object is currently open, use the
1482           "is_open" method.
1483
1484       Overload
1485           Overloaded operations return the target object, if one exists.
1486
1487           This would set $xxx to the IO::All object:
1488
1489               my $xxx = $contents > io('file.txt');
1490
1491           While this would set $xxx to the content string:
1492
1493               my $xxx = $contents < io('file.txt');
1494

STABILITY

1496       The goal of the IO::All project is to continually refine the module to
1497       be as simple and consistent to use as possible. Therefore, in the early
1498       stages of the project, I will not hesitate to break backwards
1499       compatibility with other versions of IO::All if I can find an easier
1500       and clearer way to do a particular thing.
1501
1502       IO is tricky stuff. There is definitely more work to be done. On the
1503       other hand, this module relies heavily on very stable existing IO
1504       modules; so it may work fairly well.
1505
1506       I am sure you will find many unexpected "features". Please send all
1507       problems, ideas and suggestions to ingy@cpan.org.
1508
1509   Known Bugs and Deficiencies
1510       Not all possible combinations of objects and methods have been tested.
1511       There are many many combinations. All of the examples have been tested.
1512       If you find a bug with a particular combination of calls, let me know.
1513
1514       If you call a method that does not make sense for a particular object,
1515       the result probably won't make sense. Little attempt is made to check
1516       for improper usage.
1517

CREDITS

1519       A lot of people have sent in suggestions, that have become a part of
1520       IO::All.  Thank you.
1521
1522       Special thanks to Ian Langworth for continued testing and patching.
1523
1524       Thank you Simon Cozens for tipping me off to the overloading
1525       possibilities.
1526
1527       Finally, thanks to Autrijus Tang, for always having one more good idea.
1528
1529       (It seems IO::All of it to a lot of people!)
1530

REPOSITORY AND COMMUNITY

1532       The IO::All module can be found on CPAN and on GitHub:
1533       <http://github.com/ingydotnet/io-all-pm>.
1534
1535       Please join the IO::All discussion on #io-all on irc.perl.org.
1536

SEE ALSO

1538       •   File::Spec
1539
1540       •   File::Path
1541
1542       •   File::ReadBackwards
1543
1544       •   File::MimeInfo
1545
1546       •   IO::Handle
1547
1548       •   IO::File
1549
1550       •   IO::Dir
1551
1552       •   IO::Socket
1553
1554       •   Tie::File
1555

AUTHOR

1557       Ingy döt Net <ingy@cpan.org>
1558
1560       Copyright 2004-2017. Ingy döt Net.
1561
1562       This program is free software; you can redistribute it and/or modify it
1563       under the same terms as Perl itself.
1564
1565       See <http://www.perl.com/perl/misc/Artistic.html>
1566
1567
1568
1569perl v5.34.0                      2021-07-22                        IO::All(3)
Impressum