Debian Codegraph @

README

raw
1 NAME
2
3 IO::All - IO::All to Larry Wall!
4
5 VERSION
6
7 This document describes IO::All version 0.87.
8
9 SYNOPSIS
10
11 First, some safe examples:
12
13 use IO::All;
14
15 # Some of the many ways to read a whole file into a scalar
16 $contents = io->file('file.txt')->slurp; # Read an entire file
17 @files = io->dir('lib')->all; # Get a list of files
18 $tail = io->pipe('-| tail app.log'); # Open a pipe to a command
19 $line = $tail->getline; # Read from the pipe
20
21 That said, there are a lot more things that are very convenient and
22 will help you write code very quickly, though they should be used
23 judiciously:
24
25 use IO::All; # Let the madness begin...
26
27 # Some of the many ways to read a whole file into a scalar
28 io('file.txt') > $contents; # Overloaded "arrow"
29 $contents < io 'file.txt'; # Flipped but same operation
30 $io = io 'file.txt'; # Create a new IO::All object
31 $contents = $$io; # Overloaded scalar dereference
32 $contents = $io->all; # A method to read everything
33 $contents = $io->slurp; # Another method for that
34 $contents = join '', $io->getlines; # Join the separate lines
35 $contents = join '', map "$_\n", @$io; # Same. Overloaded array deref
36 $io->tie; # Tie the object as a handle
37 $contents = join '', <$io>; # And use it in builtins
38 # and the list goes on ...
39
40 # Other file operations:
41 @lines = io('file.txt')->slurp; # List context slurp
42 $content > io('file.txt'); # Print to a file
43 io('file.txt')->print($content, $more); # (ditto)
44 $content >> io('file.txt'); # Append to a file
45 io('file.txt')->append($content); # (ditto)
46 $content << $io; # Append to a string
47 io('copy.txt') < io('file.txt'); $ Copy a file
48 io('file.txt') > io('copy.txt'); # Invokes File::Copy
49 io('more.txt') >> io('all.txt'); # Add on to a file
50 io('dir/') < io('file.txt'); $ Copy a file to a directory
51 io('file.txt') > io('dir/'); # Invokes File::Copy
52 io('more.txt') >> io('dir/'); # Add on to a file in the dir
53
54 # UTF-8 Support
55 $contents = io('file.txt')->utf8->all; # Turn on utf8
56 use IO::All -utf8; # Turn on utf8 for all io
57 $contents = io('file.txt')->all; # by default in this package.
58
59 # General Encoding Support
60 $contents = io('file.txt')->encoding('big5')->all;
61 use IO::All -encoding => 'big5'; # Turn on big5 for all io
62 $contents = io('file.txt')->all; # by default in this package.
63
64 # Print the path name of a file:
65 print $io->name; # The direct method
66 print "$io"; # Object stringifies to name
67 print $io; # Quotes not needed here
68 print $io->filename; # The file portion only
69 $io->os('win32'); # change the object to be a
70 # win32 path
71 print $io->ext; # The file extension only
72 print $io->mimetype; # The mimetype, requires a
73 # working File::MimeType
74
75
76 # Read all the files/directories in a directory:
77 $io = io('my/directory/'); # Create new directory object
78 @contents = $io->all; # Get all contents of dir
79 @contents = @$io; # Directory as an array
80 @contents = values %$io; # Directory as a hash
81 push @contents, $subdir # One at a time
82 while $subdir = $io->next;
83
84 # Print the name and file type for all the contents above:
85 print "$_ is a " . $_->type . "\n" # Each element of @contents
86 for @contents; # is an IO::All object!!
87
88 # Print first line of each file:
89 print $_->getline # getline gets one line
90 for io('dir')->all_files; # Files only
91
92 # Print names of all files/dirs three directories deep:
93 print "$_\n" for $io->all(3); # Pass in the depth. Default=1
94
95 # Print names of all files/dirs recursively:
96 print "$_\n" for $io->all(0); # Zero means all the way down
97 print "$_\n" for $io->All; # Capitalized shortcut
98 print "$_\n" for $io->deep->all; # Another way
99
100 # There are some special file names:
101 print io('-'); # Print STDIN to STDOUT
102 io('-') > io('-'); # Do it again
103 io('-') < io('-'); # Same. Context sensitive.
104 "Bad puppy" > io('='); # Message to STDERR
105 $string_file = io('$'); # Create string based filehandle
106 $temp_file = io('?'); # Create a temporary file
107
108 # Socket operations:
109 $server = io('localhost:5555')->fork; # Create a daemon socket
110 $connection = $server->accept; # Get a connection socket
111 $input < $connection; # Get some data from it
112 "Thank you!" > $connection; # Thank the caller
113 $connection->close; # Hang up
114 io(':6666')->accept->slurp > io->devnull; # Take a complaint and file it
115
116 # DBM database operations:
117 $dbm = io 'my/database'; # Create a database object
118 print $dbm->{grocery_list}; # Hash context makes it a DBM
119 $dbm->{todo} = $new_list; # Write to database
120 $dbm->dbm('GDBM_file'); # Demand specific DBM
121 io('mydb')->mldbm->{env} = \%ENV; # MLDBM support
122
123 # Tie::File support:
124 $io = io 'file.txt';
125 $io->[42] = 'Line Forty Three'; # Change a line
126 print $io->[@$io / 2]; # Print middle line
127 @$io = reverse @$io; # Reverse lines in a file
128
129 # Stat functions:
130 printf "%s %s %s\n", # Print name, uid and size of
131 $_->name, $_->uid, $_->size # contents of current directory
132 for io('.')->all;
133 print "$_\n" for sort # Use mtime method to sort all
134 {$b->mtime <=> $a->mtime} # files under current directory
135 io('.')->All_Files; # by recent modification time.
136
137 # File::Spec support:
138 $contents < io->catfile(qw(dir file.txt)); # Portable IO operation
139
140 # Miscellaneous:
141 @lines = io('file.txt')->chomp->slurp; # Chomp as you slurp
142 @chunks =
143 io('file.txt')->separator('xxx')->slurp; # Use alternnate record sep
144 $binary = io('file.bin')->binary->all; # Read a binary file
145 io('a-symlink')->readlink->slurp; # Readlink returns an object
146 print io('foo')->absolute->pathname; # Print absolute path of foo
147
148 # IO::All External Plugin Methods
149 io("myfile") > io->("ftp://store.org"); # Upload a file using ftp
150 $html < io->http("www.google.com"); # Grab a web page
151 io('mailto:[email protected]')->print($spam); # Email a "friend"
152
153 # This is just the beginning, read on...
154
155 DESCRIPTION
156
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 determined
177 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
191 USAGE
192
193 Normally just say:
194
195 use IO::All;
196
197 and IO::All will export a single function called io, which constructs
198 all IO objects.
199
200 Note on io
201
202 The io function is a magic constructor. It is easy to use and will
203 usually do the right thing, but can also blow up easily.
204
205 It takes a single optional argument and determines what type of IO::All
206 subclass object to return. With no arguments it returns an IO::All
207 object, which has no I/O methods, but has methods to construct subclass
208 objects like IO::All::File.
209
210 In other words, these 2 statements are usually the same:
211
212 $content = io('file.txt')->all;
213 $content = io->file('file.txt')->all;
214
215 Use the first form when you are demonstrating your Perl virtues of
216 laziness and impatience, and use the second form when your job is on
217 the line.
218
219 METHOD ROLE CALL
220
221 Here is an alphabetical list of all the public methods that you can
222 call on an IO::All object.
223
224 "abs2rel", "absolute", "accept", "All", "all", "All_Dirs", "all_dirs",
225 "All_Files", "all_files", "All_Links", "all_links", "append",
226 "appendf", "appendln", "assert", "atime", "autoclose", "autoflush",
227 "backwards", "bcc", "binary", "binmode", "blksize", "blocks",
228 "block_size", "buffer", "canonpath", "case_tolerant", "catdir",
229 "catfile", "catpath", "cc", "chdir", "chomp", "clear", "close",
230 "confess", "content", "copy", "ctime", "curdir", "dbm", "deep",
231 "device", "device_id", "devnull", "dir", "domain", "empty", "ext",
232 "encoding", "eof", "errors", "file", "filename", "fileno", "filepath",
233 "filter", "fork", "from", "ftp", "get", "getc", "getline", "getlines",
234 "gid", "glob", "handle", "head", "http", "https", "inode", "io_handle",
235 "is_absolute", "is_dir", "is_dbm", "is_executable", "is_file",
236 "is_link", "is_mldbm", "is_open", "is_pipe", "is_readable",
237 "is_socket", "is_stdio", "is_string", "is_temp", "is_writable", "join",
238 "length", "link", "lock", "mailer", "mailto", "mimetype", "mkdir",
239 "mkpath", "mldbm", "mode", "modes", "mtime", "name", "new", "next",
240 "nlink", "open", "os" "password", "path", "pathname", "perms", "pipe",
241 "port", "print", "printf", "println", "put", "rdonly", "rdwr", "read",
242 "readdir", "readlink", "recv", "rel2abs", "relative", "rename",
243 "request", "response", "rmdir", "rmtree", "rootdir", "scalar", "seek",
244 "send", "separator", "shutdown", "size", "slurp", "socket", "sort",
245 "splitdir", "splitpath", "stat", "stdio", "stderr", "stdin", "stdout",
246 "string", "string_ref", "subject", "sysread", "syswrite", "tail",
247 "tell", "temp", "tie", "tmpdir", "to", "touch", "truncate", "type",
248 "user", "uid", "unlink", "unlock", "updir", "uri", "utf8", "utime" and
249 "write".
250
251 Each method is documented further below.
252
253 OPERATOR OVERLOADING
254
255 IO::All objects overload a small set of Perl operators to great effect.
256 The overloads are limited to <, <<, >, >>, dereferencing operations,
257 and stringification.
258
259 Even though relatively few operations are overloaded, there is actually
260 a huge matrix of possibilities for magic. That's because the
261 overloading is sensitive to the types, position and context of the
262 arguments, and an IO::All object can be one of many types.
263
264 The most important overload to become familiar with is stringification.
265 IO::All objects stringify to their file or directory name. Here we
266 print the contents of the current directory:
267
268 perl -MIO::All -le 'print for io(".")->all'
269
270 is the same as:
271
272 perl -MIO::All -le 'print $_->name for io(".")->all'
273
274 Stringification is important because it allows IO::All operations to
275 return objects when they might otherwise return file names. Then the
276 recipient can use the result either as an object or a string.
277
278 > and < move data between objects in the direction pointed to by the
279 operator.
280
281 $content1 < io('file1');
282 $content1 > io('file2');
283 io('file2') > $content3;
284 io('file3') < $content3;
285 io('file3') > io('file4');
286 io('file5') < io('file4');
287
288 >> and << do the same thing except the recipient string or file is
289 appended to.
290
291 An IO::All file used as an array reference becomes tied using
292 Tie::File:
293
294 $file = io "file";
295 # Print last line of file
296 print $file->[-1];
297 # Insert new line in middle of file
298 $file->[$#$file / 2] = 'New line';
299
300 An IO::All file used as a hash reference becomes tied to a DBM class:
301
302 io('mydbm')->{ingy} = 'YAML';
303
304 An IO::All directory used as an array reference, will expose each file
305 or subdirectory as an element of the array.
306
307 print "$_\n" for @{io 'dir'};
308
309 IO::All directories used as hash references have file names as keys,
310 and IO::All objects as values:
311
312 print io('dir')->{'foo.txt'}->slurp;
313
314 Files used as scalar references get slurped:
315
316 print ${io('dir')->{'foo.txt'}};
317
318 Not all combinations of operations and object types are supported. Some
319 just haven't been added yet, and some just don't make sense. If you use
320 an invalid combination, an error will be thrown.
321
322 COOKBOOK
323
324 This section describes some various things that you can easily cook up
325 with IO::All.
326
327 File Locking
328
329 IO::All makes it very easy to lock files. Just use the lock method.
330 Here's a standalone program that demonstrates locking for both write
331 and read:
332
333 use IO::All;
334 my $io1 = io('myfile')->lock;
335 $io1->println('line 1');
336
337 fork or do {
338 my $io2 = io('myfile')->lock;
339 print $io2->slurp;
340 exit;
341 };
342
343 sleep 1;
344 $io1->println('line 2');
345 $io1->println('line 3');
346 $io1->unlock;
347
348 There are a lot of subtle things going on here. An exclusive lock is
349 issued for $io1 on the first println. That's because the file isn't
350 actually opened until the first IO operation.
351
352 When the child process tries to read the file using $io2, there is a
353 shared lock put on it. Since $io1 has the exclusive lock, the slurp
354 blocks.
355
356 The parent process sleeps just to make sure the child process gets a
357 chance. The parent needs to call unlock or close to release the lock.
358 If all goes well the child will print 3 lines.
359
360 In-place Editing
361
362 Because an IO::All object can be used as an array reference, operations
363 on arrays are supported transparently (using Tie::File) so a file can
364 be modified in the same way you would modify an array.
365
366 > cat > x.txt
367 The sexy saxophone,
368
369 got the axe.
370 ^d
371
372 > perl -MIO::All -e 'map { s/x/X/g; $_ } @{ io(shift) }' x.txt
373 > cat x.txt
374 The seXy saXophone,
375
376 got the aXe.
377
378 This one liner uses shift() to grab the file from STDIN and create an io
379 object that is dereferenced using @{ } and fed to map() like any perl array
380 reference.
381
382 Round Robin
383
384 This simple example will read lines from a file forever. When the last
385 line is read, it will reopen the file and read the first one again.
386
387 my $io = io 'file1.txt';
388 $io->autoclose(1);
389 while (my $line = $io->getline || $io->getline) {
390 print $line;
391 }
392
393 Reading Backwards
394
395 If you call the backwards method on an IO::All object, the getline and
396 getlines will work in reverse. They will read the lines in the file
397 from the end to the beginning.
398
399 my @reversed;
400 my $io = io('file1.txt');
401 $io->backwards;
402 while (my $line = $io->getline) {
403 push @reversed, $line;
404 }
405
406 or more simply:
407
408 my @reversed = io('file1.txt')->backwards->getlines;
409
410 The backwards method returns the IO::All object so that you can chain
411 the calls.
412
413 NOTE: This operation requires that you have the File::ReadBackwards
414 module installed.
415
416 Client/Server Sockets
417
418 IO::All makes it really easy to write a forking socket server and a
419 client to talk to it.
420
421 In this example, a server will return 3 lines of text, to every client
422 that calls it. Here is the server code:
423
424 use IO::All;
425
426 my $socket = io(':12345')->fork->accept;
427 $socket->print($_) while <DATA>;
428 $socket->close;
429
430 __DATA__
431 On your mark,
432 Get set,
433 Go!
434
435 Here is the client code:
436
437 use IO::All;
438
439 my $io = io('localhost:12345');
440 print while $_ = $io->getline;
441
442 You can run the server once, and then run the client repeatedly (in
443 another terminal window). It should print the 3 data lines each time.
444
445 Note that it is important to close the socket if the server is forking,
446 or else the socket won't go out of scope and close.
447
448 A Tiny Web Server
449
450 Here is how you could write a simplistic web server that works with
451 static and dynamic pages:
452
453 perl -MIO::All -e 'io(":8080")->fork->accept->(sub { $_[0] < io(-x $1 ? "./$1 |" : $1) if /^GET \/(.*) / })'
454
455 There is are a lot of subtle things going on here. First we accept a
456 socket and fork the server. Then we overload the new socket as a code
457 ref. This code ref takes one argument, another code ref, which is used
458 as a callback.
459
460 The callback is called once for every line read on the socket. The line
461 is put into $_ and the socket itself is passed in to the callback.
462
463 Our callback is scanning the line in $_ for an HTTP GET request. If one
464 is found it parses the file name into $1. Then we use $1 to create an
465 new IO::All file object... with a twist. If the file is executable
466 (-x), then we create a piped command as our IO::All object. This
467 somewhat approximates CGI support.
468
469 Whatever the resulting object is, we direct the contents back at our
470 socket which is in $_[0]. Pretty simple, eh?
471
472 DBM Files
473
474 IO::All file objects used as a hash reference, treat the file as a DBM
475 tied to a hash. Here I write my DB record to STDERR:
476
477 io("names.db")->{ingy} > io('=');
478
479 Since their are several DBM formats available in Perl, IO::All picks
480 the first one of these that is installed on your system:
481
482 DB_File GDBM_File NDBM_File ODBM_File SDBM_File
483
484 You can override which DBM you want for each IO::All object:
485
486 my @keys = keys %{io('mydbm')->dbm('SDBM_File')};
487
488 File Subclassing
489
490 Subclassing is easy with IO::All. Just create a new module and use
491 IO::All as the base class, like this:
492
493 package NewModule;
494 use IO::All -base;
495
496 You need to do it this way so that IO::All will export the io function.
497 Here is a simple recipe for subclassing:
498
499 IO::Dumper inherits everything from IO::All and adds an extra method
500 called dump, which will dump a data structure to the file we specify in
501 the io function. Since it needs Data::Dumper to do the dumping, we
502 override the open method to require Data::Dumper and then pass control
503 to the real open.
504
505 First the code using the module:
506
507 use IO::Dumper;
508
509 io('./mydump')->dump($hash);
510
511 And next the IO::Dumper module itself:
512
513 package IO::Dumper;
514 use IO::All -base;
515 use Data::Dumper;
516
517 sub dump {
518 my $self = shift;
519 Dumper(@_) > $self;
520 }
521
522 1;
523
524 Inline Subclassing
525
526 This recipe does the same thing as the previous one, but without
527 needing to write a separate module. The only real difference is the
528 first line. Since you don't "use" IO::Dumper, you need to still call
529 its import method manually.
530
531 IO::Dumper->import;
532 io('./mydump')->dump($hash);
533
534 package IO::Dumper;
535 use IO::All -base;
536 use Data::Dumper;
537
538 sub dump {
539 my $self = shift;
540 Dumper(@_) > $self;
541 }
542
543 THE IO::ALL METHODS
544
545 This section gives a full description of all of the methods that you
546 can call on IO::All objects. The methods have been grouped into
547 subsections based on object construction, option settings,
548 configuration, action methods and support for specific modules.
549
550 Object Construction and Initialization Methods
551
552 new
553
554 There are three ways to create a new IO::All object. The first is
555 with the special function io which really just calls IO::All->new.
556 The second is by calling new as a class method. The third is calling
557 new as an object instance method. In this final case, the new objects
558 attributes are copied from the instance object.
559
560 io(file-descriptor);
561 IO::All->new(file-descriptor);
562 $io->new(file-descriptor);
563
564 All three forms take a single argument, a file descriptor. A file
565 descriptor can be any of the following:
566
567 - A file name
568 - A file handle
569 - A directory name
570 - A directory handle
571 - A typeglob reference
572 - A piped shell command. eg '| ls -al'
573 - A socket domain/port. eg 'perl.com:5678'
574 - '-' means STDIN or STDOUT (depending on usage)
575 - '=' means STDERR
576 - '$' means an in memory filehandle object
577 - '?' means a temporary file
578 - A URI including: http, https, ftp and mailto
579 - An IO::All object
580
581 If you provide an IO::All object, you will simply get that same
582 object returned from the constructor.
583
584 If no file descriptor is provided, an object will still be created,
585 but it must be defined by one of the following methods before it can
586 be used for I/O:
587
588 file
589
590 io->file("path/to/my/file.txt");
591
592 Using the file method sets the type of the object to file and sets
593 the pathname of the file if provided.
594
595 It might be important to use this method if you had a file whose name
596 was '- ', or if the name might otherwise be confused with a directory
597 or a socket. In this case, either of these statements would work the
598 same:
599
600 my $file = io('-')->file;
601 my $file = io->file('-');
602
603 dir
604
605 io->dir($dir_name);
606
607 Make the object be of type directory.
608
609 socket
610
611 io->socket("${domain}:${port}");
612
613 Make the object be of type socket.
614
615 link
616
617 io->link($link_name);
618
619 Make the object be of type link.
620
621 pipe
622
623 io->pipe($pipe_command);
624
625 Make the object be of type pipe. The following three statements are
626 equivalent:
627
628 my $io = io('ls -l |');
629 my $io = io('ls -l')->pipe;
630 my $io = io->pipe('ls -l');
631
632 dbm
633
634 This method takes the names of zero or more DBM modules. The first
635 one that is available is used to process the dbm file.
636
637 io('mydbm')->dbm('NDBM_File', 'SDBM_File')->{author} = 'ingy';
638
639 If no module names are provided, the first available of the following
640 is used:
641
642 DB_File GDBM_File NDBM_File ODBM_File SDBM_File
643
644 mldbm
645
646 Similar to the dbm method, except create a Multi Level DBM object
647 using the MLDBM module.
648
649 This method takes the names of zero or more DBM modules and an
650 optional serialization module. The first DBM module that is available
651 is used to process the MLDBM file. The serialization module can be
652 Data::Dumper, Storable or FreezeThaw.
653
654 io('mymldbm')->mldbm('GDBM_File', 'Storable')->{author} =
655 {nickname => 'ingy'};
656
657 string
658
659 Make the object be an in memory filehandle. These are equivalent:
660
661 my $io = io('$');
662 my $io = io->string;
663
664 temp
665
666 Make the object represent a temporary file. It will automatically be
667 open for both read and write.
668
669 stdio
670
671 Make the object represent either STDIN or STDOUT depending on how it
672 is used subsequently. These are equivalent:
673
674 my $io = io('-');
675 my $io = io->stdin;
676
677 stdin
678
679 Make the object represent STDIN.
680
681 stdout
682
683 Make the object represent STDOUT.
684
685 stderr
686
687 Make the object represent STDERR.
688
689 handle
690
691 io->handle($io_handle);
692
693 Forces the object to be created from an pre-existing IO handle. You
694 can chain calls together to indicate the type of handle:
695
696 my $file_object = io->file->handle($file_handle);
697 my $dir_object = io->dir->handle($dir_handle);
698
699 http
700
701 Make the object represent an HTTP URI. Requires IO-All-LWP.
702
703 https
704
705 Make the object represent an HTTPS URI. Requires IO-All-LWP.
706
707 ftp
708
709 Make the object represent an FTP URI. Requires IO-All-LWP.
710
711 mailto
712
713 Make the object represent a mailto: URI. Requires IO-All-Mailto.
714
715 If you need to use the same options to create a lot of objects, and
716 don't want to duplicate the code, just create a dummy object with the
717 options you want, and use that object to spawn other objects.
718
719 my $lt = io->lock->tie;
720 ...
721 my $io1 = $lt->new('file1');
722 my $io2 = $lt->new('file2');
723
724 Since the new method copies attributes from the calling object, both
725 $io1 and $io2 will be locked and tied.
726
727 Option Setting Methods
728
729 The following methods don't do any actual IO, but they specify options
730 about how the IO should be done.
731
732 Each option can take a single argument of 0 or 1. If no argument is
733 given, the value 1 is assumed. Passing 0 turns the option off.
734
735 All of these options return the object reference that was used to
736 invoke them. This is so that the option methods can be chained
737 together. For example:
738
739 my $io = io('path/file')->tie->assert->chomp->lock;
740
741 absolute
742
743 Indicates that the pathname for the object should be made absolute.
744
745 # Print the full path of the current working directory
746 # (like pwd).
747
748 use IO::All;
749
750 print io->curdir->absolute;
751
752 assert
753
754 This method ensures that the path for a file or directory actually
755 exists before the file is open. If the path does not exist, it is
756 created.
757
758 For example, here is a program called "create-cat-to" that outputs to
759 a file that it creates.
760
761 #!/usr/bin/perl
762
763 # create-cat-to.pl
764 # cat to a file that can be created.
765
766 use strict;
767 use warnings;
768
769 use IO::All;
770
771 my $filename = shift(@ARGV);
772
773 # Create a file called $filename, including all leading components.
774 io('-') > io->file($filename)->assert;
775
776 Here's an example use of it:
777
778 $ ls -l
779 total 0
780 $ echo "Hello World" | create-cat-to one/two/three/four.txt
781 $ ls -l
782 total 4
783 drwxr-xr-x 3 shlomif shlomif 4096 2010-10-14 18:03 one/
784 $ cat one/two/three/four.txt
785 Hello World
786 $
787
788 autoclose
789
790 By default, IO::All will close an object opened for input when EOF is
791 reached. By closing the handle early, one can immediately do other
792 operations on the object without first having to close it.
793
794 This option is on by default, so if you don't want this behaviour,
795 say so like this:
796
797 $io->autoclose(0);
798
799 The object will then be closed when $io goes out of scope, or you
800 manually call $io->close.
801
802 autoflush
803
804 Proxy for IO::Handle::autoflush
805
806 backwards
807
808 Sets the object to 'backwards' mode. All subsequent getline
809 operations will read backwards from the end of the file.
810
811 Requires the File::ReadBackwards CPAN module.
812
813 binary
814
815 Adds :raw to the list of PerlIO layers applied after open, and
816 applies it immediately on an open handle.
817
818 chdir
819
820 chdir() to the pathname of a directory object. When object goes out
821 of scope, chdir back to starting directory.
822
823 chomp
824
825 Indicates that all operations that read lines should chomp the lines.
826 If the separator method has been called, chomp will remove that value
827 from the end of each record.
828
829 Note that chomp may cause the following idiom to halt prematurely
830 (e.g., if separator is \n (the default) and chomp is in effect, then
831 this command will stop reading at the first blank line):
832
833 while ( my $line = $io->getline ) {...}
834
835 Try the following instead:
836
837 while ( defined(my $line = $io->getline) ) {...}
838
839 confess
840
841 Errors should be reported with the very detailed Carp::confess
842 function.
843
844 deep
845
846 Indicates that calls to the all family of methods should search
847 directories as deep as possible.
848
849 fork
850
851 Indicates that the process should automatically be forked inside the
852 accept socket method.
853
854 lock
855
856 Indicate that operations on an object should be locked using flock.
857
858 rdonly
859
860 This option indicates that certain operations like DBM and Tie::File
861 access should be done in read-only mode.
862
863 rdwr
864
865 This option indicates that DBM and MLDBM files should be opened in
866 read/write mode.
867
868 relative
869
870 Indicates that the pathname for the object should be made relative.
871 If passed an argument, path will be made relative to passed argument.
872
873 sort
874
875 Indicates whether objects returned from one of the all methods will
876 be in sorted order by name. True by default.
877
878 tie
879
880 Indicate that the object should be tied to itself, thus allowing it
881 to be used as a filehandle in any of Perl's builtin IO operations.
882
883 my $io = io('foo')->tie;
884 @lines = <$io>;
885
886 utf8
887
888 Adds :encoding(UTF-8) to the list of PerlIO layers applied after
889 open, and applies it immediately on an open handle.
890
891 Configuration Methods
892
893 The following methods don't do any actual I/O, but they set specific
894 values to configure the IO::All object.
895
896 If these methods are passed no argument, they will return their current
897 value. If arguments are passed they will be used to set the current
898 value, and the object reference will be returned for potential method
899 chaining.
900
901 bcc
902
903 Set the Bcc field for a mailto object.
904
905 binmode
906
907 Adds the specified layer to the list of PerlIO layers applied after
908 open, and applies it immediately on an open handle. Does a bare
909 binmode when called without argument.
910
911 block_size
912
913 The default length to be used for read and sysread calls. Defaults to
914 1024.
915
916 buffer
917
918 Returns a reference to the internal buffer, which is a scalar. You
919 can use this method to set the buffer to a scalar of your choice.
920 (You can just pass in the scalar, rather than a reference to it.)
921
922 This is the buffer that read and write will use by default.
923
924 You can easily have IO::All objects use the same buffer:
925
926 my $input = io('abc');
927 my $output = io('xyz');
928 my $buffer;
929 $output->buffer($input->buffer($buffer));
930 $output->write while $input->read;
931
932 cc
933
934 Set the Cc field for a mailto object.
935
936 content
937
938 Get or set the content for an LWP operation manually.
939
940 domain
941
942 Set the domain name or ip address that a socket should use.
943
944 encoding
945
946 Adds the specified encoding to the list of PerlIO layers applied
947 after open, and applies it immediately on an open handle. Requires an
948 argument.
949
950 errors
951
952 Use this to set a subroutine reference that gets called when an
953 internal error is thrown.
954
955 filter
956
957 Use this to set a subroutine reference that will be used to grep
958 which objects get returned on a call to one of the all methods. For
959 example:
960
961 my @odd = io->curdir->filter(sub {$_->size % 2})->All_Files;
962
963 @odd will contain all the files under the current directory whose
964 size is an odd number of bytes.
965
966 from
967
968 Indicate the sender for a mailto object.
969
970 mailer
971
972 Set the mailer program for a mailto transaction. Defaults to
973 'sendmail'.
974
975 mode
976
977 Set the mode for which the file should be opened. Examples:
978
979 $io->mode('>>')->open;
980 $io->mode(O_RDONLY);
981
982 my $log_appender = io->file('/var/log/my-application.log')
983 ->mode('>>')->open();
984
985 $log_appender->print("Stardate 5987.6: Mission accomplished.");
986
987 name
988
989 Set or get the name of the file or directory represented by the
990 IO::All object.
991
992 password
993
994 Set the password for an LWP transaction.
995
996 perms
997
998 Sets the permissions to be used if the file/directory needs to be
999 created.
1000
1001 port
1002
1003 Set the port number that a socket should use.
1004
1005 request
1006
1007 Manually specify the request object for an LWP transaction.
1008
1009 response
1010
1011 Returns the resulting response object from an LWP transaction.
1012
1013 separator
1014
1015 Sets the record (line) separator to whatever value you pass it.
1016 Default is \n. Affects the chomp setting too.
1017
1018 string_ref
1019
1020 Returns a reference to the internal string that is acting like a
1021 file.
1022
1023 subject
1024
1025 Set the subject for a mailto transaction.
1026
1027 to
1028
1029 Set the recipient address for a mailto request.
1030
1031 uri
1032
1033 Direct access to the URI used in LWP transactions.
1034
1035 user
1036
1037 Set the user name for an LWP transaction.
1038
1039 IO Action Methods
1040
1041 These are the methods that actually perform I/O operations on an
1042 IO::All object. The stat methods and the File::Spec methods are
1043 documented in separate sections below.
1044
1045 accept
1046
1047 For sockets. Opens a server socket (LISTEN => 1, REUSE => 1). Returns
1048 an IO::All socket object that you are listening on.
1049
1050 If the fork method was called on the object, the process will
1051 automatically be forked for every connection.
1052
1053 all
1054
1055 Read all contents into a single string.
1056
1057 compare(io('file1')->all, io('file2')->all);
1058
1059 all (For directories)
1060
1061 Returns a list of IO::All objects for all files and subdirectories in
1062 a directory.
1063
1064 '.' and '..' are excluded.
1065
1066 Takes an optional argument telling how many directories deep to
1067 search. The default is 1. Zero (0) means search as deep as possible.
1068
1069 The filter method can be used to limit the results.
1070
1071 The items returned are sorted by name unless ->sort(0) is used.
1072
1073 All
1074
1075 Same as all(0).
1076
1077 all_dirs
1078
1079 Same as all, but only return directories.
1080
1081 All_Dirs
1082
1083 Same as all_dirs(0).
1084
1085 all_files
1086
1087 Same as all, but only return files.
1088
1089 All_Files
1090
1091 Same as all_files(0).
1092
1093 all_links
1094
1095 Same as all, but only return links.
1096
1097 All_Links
1098
1099 Same as all_links(0).
1100
1101 append
1102
1103 Same as print, but sets the file mode to '>>'.
1104
1105 appendf
1106
1107 Same as printf, but sets the file mode to '>>'.
1108
1109 appendln
1110
1111 Same as println, but sets the file mode to '>>'.
1112
1113 clear
1114
1115 Clear the internal buffer. This method is called by write after it
1116 writes the buffer. Returns the object reference for chaining.
1117
1118 close
1119
1120 Close will basically unopen the object, which has different meanings
1121 for different objects. For files and directories it will close and
1122 release the handle. For sockets it calls shutdown. For tied things it
1123 unties them, and it unlocks locked things.
1124
1125 copy
1126
1127 Copies the object to the path passed. Works on both files and
1128 directories, but directories require File::Copy::Recursive to be
1129 installed.
1130
1131 empty
1132
1133 Returns true if a file exists but has no size, or if a directory
1134 exists but has no contents.
1135
1136 eof
1137
1138 Proxy for IO::Handle::eof
1139
1140 ext
1141
1142 Returns the extension of the file. Can also be spelled as extension
1143
1144 exists
1145
1146 Returns whether or not the file or directory exists.
1147
1148 filename
1149
1150 Return the name portion of the file path in the object. For example:
1151
1152 io('my/path/file.txt')->filename;
1153
1154 would return file.txt.
1155
1156 fileno
1157
1158 Proxy for IO::Handle::fileno
1159
1160 filepath
1161
1162 Return the path portion of the file path in the object. For example:
1163
1164 io('my/path/file.txt')->filepath;
1165
1166 would return my/path.
1167
1168 get
1169
1170 Perform an LWP GET request manually.
1171
1172 getc
1173
1174 Proxy for IO::Handle::getc
1175
1176 getline
1177
1178 Calls IO::File::getline. You can pass in an optional record
1179 separator.
1180
1181 getlines
1182
1183 Calls IO::File::getlines. You can pass in an optional record
1184 separator.
1185
1186 glob
1187
1188 Creates IO::All objects for the files matching the glob in the
1189 IO::All::Dir. For example:
1190
1191 io->dir($ENV{HOME})->glob('*.txt')
1192
1193 head
1194
1195 Return the first 10 lines of a file. Takes an optional argument which
1196 is the number of lines to return. Works as expected in list and
1197 scalar context. Is subject to the current line separator.
1198
1199 io_handle
1200
1201 Direct access to the actual IO::Handle object being used on an opened
1202 IO::All object.
1203
1204 is_dir
1205
1206 Returns boolean telling whether or not the IO::All object represents
1207 a directory.
1208
1209 is_executable
1210
1211 Returns true if file or directory is executable.
1212
1213 is_dbm
1214
1215 Returns boolean telling whether or not the IO::All object represents
1216 a dbm file.
1217
1218 is_file
1219
1220 Returns boolean telling whether or not the IO::All object represents
1221 a file.
1222
1223 is_link
1224
1225 Returns boolean telling whether or not the IO::All object represents
1226 a symlink.
1227
1228 is_mldbm
1229
1230 Returns boolean telling whether or not the IO::All object represents
1231 a mldbm file.
1232
1233 is_open
1234
1235 Indicates whether the IO::All is currently open for input/output.
1236
1237 is_pipe
1238
1239 Returns boolean telling whether or not the IO::All object represents
1240 a pipe operation.
1241
1242 is_readable
1243
1244 Returns true if file or directory is readable.
1245
1246 is_socket
1247
1248 Returns boolean telling whether or not the IO::All object represents
1249 a socket.
1250
1251 is_stdio
1252
1253 Returns boolean telling whether or not the IO::All object represents
1254 a STDIO file handle.
1255
1256 is_string
1257
1258 Returns boolean telling whether or not the IO::All object represents
1259 an in memory filehandle.
1260
1261 is_temp
1262
1263 Returns boolean telling whether or not the IO::All object represents
1264 a temporary file.
1265
1266 is_writable
1267
1268 Returns true if file or directory is writable. Can also be spelled as
1269 is_writeable.
1270
1271 length
1272
1273 Return the length of the internal buffer.
1274
1275 mimetype
1276
1277 Return the mimetype of the file.
1278
1279 Requires a working installation of the File::MimeInfo CPAN module.
1280
1281 mkdir
1282
1283 Create the directory represented by the object.
1284
1285 mkpath
1286
1287 Create the directory represented by the object, when the path
1288 contains more than one directory that doesn't exist. Proxy for
1289 File::Path::mkpath.
1290
1291 next
1292
1293 For a directory, this will return a new IO::All object for each file
1294 or subdirectory in the directory. Return undef on EOD.
1295
1296 open
1297
1298 Open the IO::All object. Takes two optional arguments mode and perms,
1299 which can also be set ahead of time using the mode and perms methods.
1300
1301 NOTE: Normally you won't need to call open (or mode/perms), since
1302 this happens automatically for most operations.
1303
1304 os
1305
1306 Change the object's os representation. Valid options are: win32,
1307 unix, vms, mac, os2.
1308
1309 pathname
1310
1311 Return the absolute or relative pathname for a file or directory,
1312 depending on whether object is in absolute or relative mode.
1313
1314 print
1315
1316 Proxy for IO::Handle::print
1317
1318 printf
1319
1320 Proxy for IO::Handle::printf
1321
1322 println
1323
1324 Same as print, but adds newline to each argument unless it already
1325 ends with one.
1326
1327 put
1328
1329 Perform an LWP PUT request manually.
1330
1331 read
1332
1333 This method varies depending on its context. Read carefully (no pun
1334 intended).
1335
1336 For a file, this will proxy IO::File::read. This means you must pass
1337 it a buffer, a length to read, and optionally a buffer offset for
1338 where to put the data that is read. The function returns the length
1339 actually read (which is zero at EOF).
1340
1341 If you don't pass any arguments for a file, IO::All will use its own
1342 internal buffer, a default length, and the offset will always point
1343 at the end of the buffer. The buffer can be accessed with the buffer
1344 method. The length can be set with the block_size method. The default
1345 length is 1024 bytes. The clear method can be called to clear the
1346 buffer.
1347
1348 For a directory, this will proxy IO::Dir::read.
1349
1350 readdir
1351
1352 Similar to the Perl readdir builtin. In scalar context, return the
1353 next directory entry (ie file or directory name), or undef on end of
1354 directory. In list context, return all directory entries.
1355
1356 Note that readdir does not return the special . and .. entries.
1357
1358 readline
1359
1360 Same as getline.
1361
1362 readlink
1363
1364 Calls Perl's readlink function on the link represented by the object.
1365 Instead of returning the file path, it returns a new IO::All object
1366 using the file path.
1367
1368 recv
1369
1370 Proxy for IO::Socket::recv
1371
1372 rename
1373
1374 my $new = $io->rename('new-name');
1375
1376 Calls Perl's rename function and returns an IO::All object for the
1377 renamed file. Returns false if the rename failed.
1378
1379 rewind
1380
1381 Proxy for IO::Dir::rewind
1382
1383 rmdir
1384
1385 Delete the directory represented by the IO::All object.
1386
1387 rmtree
1388
1389 Delete the directory represented by the IO::All object and all the
1390 files and directories beneath it. Proxy for File::Path::rmtree.
1391
1392 scalar
1393
1394 Deprecated. Same as all().
1395
1396 seek
1397
1398 Proxy for IO::Handle::seek. If you use seek on an unopened file, it
1399 will be opened for both read and write.
1400
1401 send
1402
1403 Proxy for IO::Socket::send
1404
1405 shutdown
1406
1407 Proxy for IO::Socket::shutdown
1408
1409 slurp
1410
1411 Read all file content in one operation. Returns the file content as a
1412 string. In list context returns every line in the file.
1413
1414 stat
1415
1416 Proxy for IO::Handle::stat
1417
1418 sysread
1419
1420 Proxy for IO::Handle::sysread
1421
1422 syswrite
1423
1424 Proxy for IO::Handle::syswrite
1425
1426 tail
1427
1428 Return the last 10 lines of a file. Takes an optional argument which
1429 is the number of lines to return. Works as expected in list and
1430 scalar context. Is subject to the current line separator.
1431
1432 tell
1433
1434 Proxy for IO::Handle::tell
1435
1436 throw
1437
1438 This is an internal method that gets called whenever there is an
1439 error. It could be useful to override it in a subclass, to provide
1440 more control in error handling.
1441
1442 touch
1443
1444 Update the atime and mtime values for a file or directory. Creates an
1445 empty file if the file does not exist.
1446
1447 truncate
1448
1449 Proxy for IO::Handle::truncate
1450
1451 type
1452
1453 Returns a string indicated the type of io object. Possible values
1454 are:
1455
1456 file
1457 dir
1458 link
1459 socket
1460 string
1461 pipe
1462
1463 Returns undef if type is not determinable.
1464
1465 unlink
1466
1467 Unlink (delete) the file represented by the IO::All object.
1468
1469 NOTE: You can unlink a file after it is open, and continue using it
1470 until it is closed.
1471
1472 unlock
1473
1474 Release a lock from an object that used the lock method.
1475
1476 utime
1477
1478 Proxy for the utime Perl function.
1479
1480 write
1481
1482 Opposite of read for file operations only.
1483
1484 NOTE: When used with the automatic internal buffer, write will clear
1485 the buffer after writing it.
1486
1487 Stat Methods
1488
1489 This methods get individual values from a stat call on the file,
1490 directory or handle represented by the IO::All object.
1491
1492 atime
1493
1494 Last access time in seconds since the epoch
1495
1496 blksize
1497
1498 Preferred block size for file system I/O
1499
1500 blocks
1501
1502 Actual number of blocks allocated
1503
1504 ctime
1505
1506 Inode change time in seconds since the epoch
1507
1508 device
1509
1510 Device number of filesystem
1511
1512 device_id
1513
1514 Device identifier for special files only
1515
1516 gid
1517
1518 Numeric group id of file's owner
1519
1520 inode
1521
1522 Inode number
1523
1524 modes
1525
1526 File mode - type and permissions
1527
1528 mtime
1529
1530 Last modify time in seconds since the epoch
1531
1532 nlink
1533
1534 Number of hard links to the file
1535
1536 size
1537
1538 Total size of file in bytes
1539
1540 uid
1541
1542 Numeric user id of file's owner
1543
1544 File::Spec Methods
1545
1546 These methods are all adaptations from File::Spec. Each method actually
1547 does call the matching File::Spec method, but the arguments and return
1548 values differ slightly. Instead of being file and directory names, they
1549 are IO::All objects. Since IO::All objects stringify to their names,
1550 you can generally use the methods just like File::Spec.
1551
1552 abs2rel
1553
1554 Returns the relative path for the absolute path in the IO::All
1555 object. Can take an optional argument indicating the base path.
1556
1557 canonpath
1558
1559 Returns the canonical path for the IO::All object. The canonical path
1560 is the fully resolved path if the file exists, so any symlinks will
1561 be resolved.
1562
1563 case_tolerant
1564
1565 Returns 0 or 1 indicating whether the file system is case tolerant.
1566 Since an active IO::All object is not needed for this function, you
1567 can code it like:
1568
1569 IO::All->case_tolerant;
1570
1571 or more simply:
1572
1573 io->case_tolerant;
1574
1575 catdir
1576
1577 Concatenate the directory components together, and return a new
1578 IO::All object representing the resulting directory.
1579
1580 catfile
1581
1582 Concatenate the directory and file components together, and return a
1583 new IO::All object representing the resulting file.
1584
1585 my $contents = io->catfile(qw(dir subdir file))->slurp;
1586
1587 This is a very portable way to read dir/subdir/file.
1588
1589 catpath
1590
1591 Concatenate the volume, directory and file components together, and
1592 return a new IO::All object representing the resulting file.
1593
1594 curdir
1595
1596 Returns an IO::All object representing the current directory.
1597
1598 devnull
1599
1600 Returns an IO::All object representing the /dev/null file.
1601
1602 is_absolute
1603
1604 Returns 0 or 1 indicating whether the name field of the IO::All
1605 object is an absolute path.
1606
1607 join
1608
1609 Same as catfile.
1610
1611 path
1612
1613 Returns a list of IO::All directory objects for each directory in
1614 your path.
1615
1616 rel2abs
1617
1618 Returns the absolute path for the relative path in the IO::All
1619 object. Can take an optional argument indicating the base path.
1620
1621 rootdir
1622
1623 Returns an IO::All object representing the root directory on your
1624 file system.
1625
1626 splitdir
1627
1628 Returns a list of the directory components of a path in an IO::All
1629 object.
1630
1631 splitpath
1632
1633 Returns a volume directory and file component of a path in an IO::All
1634 object.
1635
1636 tmpdir
1637
1638 Returns an IO::All object representing a temporary directory on your
1639 file system.
1640
1641 updir
1642
1643 Returns an IO::All object representing the current parent directory.
1644
1645 OPERATIONAL NOTES
1646
1647 Reblessing
1648
1649 Each IO::All object gets reblessed into an IO::All::* object as soon
1650 as IO::All can determine what type of object it should be. Sometimes
1651 it gets reblessed more than once:
1652
1653 my $io = io('mydbm.db');
1654 $io->dbm('DB_File');
1655 $io->{foo} = 'bar';
1656
1657 In the first statement, $io has a reference value of 'IO::All::File',
1658 if mydbm.db exists. In the second statement, the object is reblessed
1659 into class 'IO::All::DBM'.
1660
1661 Auto-Open
1662
1663 An IO::All object will automatically be opened as soon as there is
1664 enough contextual information to know what type of object it is, and
1665 what mode it should be opened for. This is usually when the first
1666 read or write operation is invoked but might be sooner.
1667
1668 Auto-Mode
1669
1670 The mode for an object to be opened with is determined heuristically
1671 unless specified explicitly.
1672
1673 Auto-Close
1674
1675 For input, IO::All objects will automatically be closed after EOF (or
1676 EOD). For output, the object closes when it goes out of scope.
1677
1678 To keep input objects from closing at EOF, do this:
1679
1680 $io->autoclose(0);
1681
1682 Explicit open and close
1683
1684 You can always call open and close explicitly, if you need that level
1685 of control. To test if an object is currently open, use the is_open
1686 method.
1687
1688 Overload
1689
1690 Overloaded operations return the target object, if one exists.
1691
1692 This would set $xxx to the IO::All object:
1693
1694 my $xxx = $contents > io('file.txt');
1695
1696 While this would set $xxx to the content string:
1697
1698 my $xxx = $contents < io('file.txt');
1699
1700 STABILITY
1701
1702 The goal of the IO::All project is to continually refine the module to
1703 be as simple and consistent to use as possible. Therefore, in the early
1704 stages of the project, I will not hesitate to break backwards
1705 compatibility with other versions of IO::All if I can find an easier
1706 and clearer way to do a particular thing.
1707
1708 IO is tricky stuff. There is definitely more work to be done. On the
1709 other hand, this module relies heavily on very stable existing IO
1710 modules; so it may work fairly well.
1711
1712 I am sure you will find many unexpected "features". Please send all
1713 problems, ideas and suggestions to [email protected].
1714
1715 Known Bugs and Deficiencies
1716
1717 Not all possible combinations of objects and methods have been tested.
1718 There are many many combinations. All of the examples have been tested.
1719 If you find a bug with a particular combination of calls, let me know.
1720
1721 If you call a method that does not make sense for a particular object,
1722 the result probably won't make sense. Little attempt is made to check
1723 for improper usage.
1724
1725 CREDITS
1726
1727 A lot of people have sent in suggestions, that have become a part of
1728 IO::All. Thank you.
1729
1730 Special thanks to Ian Langworth for continued testing and patching.
1731
1732 Thank you Simon Cozens for tipping me off to the overloading
1733 possibilities.
1734
1735 Finally, thanks to Autrijus Tang, for always having one more good idea.
1736
1737 (It seems IO::All of it to a lot of people!)
1738
1739 REPOSITORY AND COMMUNITY
1740
1741 The IO::All module can be found on CPAN and on GitHub:
1742 http://github.com/ingydotnet/io-all-pm.
1743
1744 Please join the IO::All discussion on #io-all on irc.perl.org.
1745
1746 SEE ALSO
1747
1748 * File::Spec
1749
1750 * File::Path
1751
1752 * File::ReadBackwards
1753
1754 * File::MimeInfo
1755
1756 * IO::Handle
1757
1758 * IO::File
1759
1760 * IO::Dir
1761
1762 * IO::Socket
1763
1764 * Tie::File
1765
1766 AUTHOR
1767
1768 Ingy döt Net <[email protected]>
1769
1770 COPYRIGHT AND LICENSE
1771
1772 Copyright 2004-2017. Ingy döt Net.
1773
1774 This program is free software; you can redistribute it and/or modify it
1775 under the same terms as Perl itself.
1776
1777 See http://www.perl.com/perl/misc/Artistic.html
1778