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