IO-All-0.54000755001750001750 012267312543 11555 5ustar00frewfrew000000000000ToDo100644001750001750 163312267312543 12431 0ustar00frewfrew000000000000IO-All-0.54== 0.42 - Can't sort io->all_files - Test on OS X - Return 0 or 1 on fail or success - Die on failure with -strict option. - Fix mst's bug - perl -MIO::All -e '${io("/tmp")}' 0.30 release - IO::All::STDIO -> IO::All::Stdio (downcase) - No dependency on Tie::File - Fix test failures - Test the interface with 3rd party modules - New methods: - file->empty dir->empty - touch - file->all - add stubs in IO::All that throw errors for these (type undetermined) - Use '=' for STDERR - Support piping open: '|foo', 'foo|' - Maybe even: '|foo|' - $io->separator - $io->ending - $io->end - $io->sep - overloading # read all files recursively $files << io('dir'); io('dir') >> $files; - email support (Mail::Send) - irc support - blog support (Atom) - http support (LWP) - ftp support - dav support - ldap support - pop support - smtp support - Serial Support - Win32::SerialPort - Device::SerialPort t000755001750001750 012267312543 11741 5ustar00frewfrew000000000000IO-All-0.54os.t100644001750001750 222712267312543 12712 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't'; use strict; use warnings; use Test::More tests => 14; use IO::All; is("".io->file(qw(foo bar baz biff))->os('unix'), 'foo/bar/baz/biff'); is("".io->file(qw(foo bar baz biff))->os('win32'), 'foo\bar\baz\biff'); is("".io->file(qw(foo bar baz biff))->os('win32')->os('unix'), 'foo/bar/baz/biff'); is("".io->file(qw(foo bar baz biff))->os('unix')->os('win32'), 'foo\bar\baz\biff'); { local $TODO = 'unix drops drive'; is("".io->file(qw(C: foo bar baz biff))->os('unix')->os('win32'), 'C:\foo\bar\baz\biff'); is("".io->dir(qw(C: foo bar baz biff))->os('unix')->os('win32'), 'C:\foo\bar\baz\biff'); } is("".io->file(qw(C: foo bar baz biff))->os('win32')->os('unix'), '/foo/bar/baz/biff'); is("".io->dir(qw(foo bar baz biff))->os('unix'), 'foo/bar/baz/biff'); is("".io->dir(qw(foo bar baz biff))->os('win32'), 'foo\bar\baz\biff'); is("".io->dir(qw(foo bar baz biff))->os('win32')->os('unix'), 'foo/bar/baz/biff'); is("".io->dir(qw(foo bar baz biff))->os('unix')->os('win32'), 'foo\bar\baz\biff'); is("".io->dir(qw(C: foo bar baz biff))->os('win32')->os('unix'), '/foo/bar/baz/biff'); is("".io->dir('')->os('unix'), ''); is("".io->file('')->os('unix'), ''); README100644001750001750 14432012267312543 12562 0ustar00frewfrew000000000000IO-All-0.54NAME IO::All - IO::All of it to Graham and Damian! SYNOPSIS use IO::All; # Let the madness begin... # Some of the many ways to read a whole file into a scalar io('file.txt') > $contents; # Overloaded "arrow" $contents < io 'file.txt'; # Flipped but same operation $io = io 'file.txt'; # Create a new IO::All object $contents = $$io; # Overloaded scalar dereference $contents = $io->all; # A method to read everything $contents = $io->slurp; # Another method for that $contents = join '', $io->getlines; # Join the separate lines $contents = join '', map "$_\n", @$io; # Same. Overloaded array deref $io->tie; # Tie the object as a handle $contents = join '', <$io>; # And use it in builtins # and the list goes on ... # Other file operations: @lines = io('file.txt')->slurp; # List context slurp $content > io('file.txt'); # Print to a file io('file.txt')->print($content, $more); # (ditto) $content >> io('file.txt'); # Append to a file io('file.txt')->append($content); # (ditto) $content << $io; # Append to a string io('copy.txt') < io('file.txt'); $ Copy a file io('file.txt') > io('copy.txt'); # Invokes File::Copy io('more.txt') >> io('all.txt'); # Add on to a file # UTF-8 Support $contents = io('file.txt')->utf8->all; # Turn on utf8 use IO::All -utf8; # Turn on utf8 for all io $contents = io('file.txt')->all; # by default in this package. # General Encoding Support $contents = io('file.txt')->encoding('big5')->all; use IO::All -encoding => 'big5'; # Turn on big5 for all io $contents = io('file.txt')->all; # by default in this package. # Print the path name of a file: print $io->name; # The direct method print "$io"; # Object stringifies to name print $io; # Quotes not needed here print $io->filename; # The file portion only $io->os('win32'); # change the object to be a # win32 path print $io->ext; # The file extension only print $io->mimetype; # The mimetype, requires a # working File::MimeType # Read all the files/directories in a directory: $io = io('my/directory/'); # Create new directory object @contents = $io->all; # Get all contents of dir @contents = @$io; # Directory as an array @contents = values %$io; # Directory as a hash push @contents, $subdir # One at a time while $subdir = $io->next; # Print the name and file type for all the contents above: print "$_ is a " . $_->type . "\n" # Each element of @contents for @contents; # is an IO::All object!! # Print first line of each file: print $_->getline # getline gets one line for io('dir')->all_files; # Files only # Print names of all files/dirs three directories deep: print "$_\n" for $io->all(3); # Pass in the depth. Default=1 # Print names of all files/dirs recursively: print "$_\n" for $io->all(0); # Zero means all the way down print "$_\n" for $io->All; # Capitalized shortcut print "$_\n" for $io->deep->all; # Another way # There are some special file names: print io('-'); # Print STDIN to STDOUT io('-') > io('-'); # Do it again io('-') < io('-'); # Same. Context sensitive. "Bad puppy" > io('='); # Message to STDERR $string_file = io('$'); # Create IO::String Object $temp_file = io('?'); # Create a temporary file # Socket operations: $server = io('localhost:5555')->fork; # Create a daemon socket $connection = $server->accept; # Get a connection socket $input < $connection; # Get some data from it "Thank you!" > $connection; # Thank the caller $connection->close; # Hang up io(':6666')->accept->slurp > io->devnull; # Take a complaint and file it # DBM database operations: $dbm = io 'my/database'; # Create a database object print $dbm->{grocery_list}; # Hash context makes it a DBM $dbm->{todo} = $new_list; # Write to database $dbm->dbm('GDBM_file'); # Demand specific DBM io('mydb')->mldbm->{env} = \%ENV; # MLDBM support # Tie::File support: $io = io 'file.txt'; $io->[42] = 'Line Forty Three'; # Change a line print $io->[@$io / 2]; # Print middle line @$io = reverse @$io; # Reverse lines in a file # Stat functions: printf "%s %s %s\n", # Print name, uid and size of $_->name, $_->uid, $_->size # contents of current directory for io('.')->all; print "$_\n" for sort # Use mtime method to sort all {$b->mtime <=> $a->mtime} # files under current directory io('.')->All_Files; # by recent modification time. # File::Spec support: $contents < io->catfile(qw(dir file.txt)); # Portable IO operation # Miscellaneous: @lines = io('file.txt')->chomp->slurp; # Chomp as you slurp @chunks = io('file.txt')->separator('xxx')->slurp; # Use alternnate record sep $binary = io('file.bin')->binary->all; # Read a binary file io('a-symlink')->readlink->slurp; # Readlink returns an object print io('foo')->absolute->pathname; # Print absolute path of foo # IO::All External Plugin Methods io("myfile") > io->("ftp://store.org"); # Upload a file using ftp $html < io->http("www.google.com"); # Grab a web page io('mailto:worst@enemy.net')->print($spam); # Email a "friend" # This is just the beginning, read on... DESCRIPTION "Graham Barr for doing it all. Damian Conway for doing it all different." IO::All combines all of the best Perl IO modules into a single nifty object oriented interface to greatly simplify your everyday Perl IO idioms. It exports a single function called "io", which returns a new IO::All object. And that object can do it all! The IO::All object is a proxy for IO::File, IO::Dir, IO::Socket, IO::String, Tie::File, File::Spec, File::Path, File::MimeInfo and File::ReadBackwards; as well as all the DBM and MLDBM modules. You can use most of the methods found in these classes and in IO::Handle (which they inherit from). IO::All adds dozens of other helpful idiomatic methods including file stat and manipulation functions. IO::All is pluggable, and modules like IO::All::LWP and IO::All::Mailto add even more functionality. Optionally, every IO::All object can be tied to itself. This means that you can use most perl IO builtins on it: readline, <>, getc, print, printf, syswrite, sysread, close. The distinguishing magic of IO::All is that it will automatically open (and close) files, directories, sockets and other IO things for you. You never need to specify the mode ('<', '>>', etc), since it is determined by the usage context. That means you can replace this: open STUFF, '<', './mystuff' or die "Can't open './mystuff' for input:\n$!"; local $/; my $stuff = ; close STUFF; with this: my $stuff < io './mystuff'; And that is a good thing! USAGE Normally just say: use IO::All; and IO::All will export a single function called "io", which constructs all IO objects. You can also pass global flags like this: use IO::All -encoding => 'big5', -foobar; Which automatically makes those method calls on every new IO object. In other words this: my $io = io('lalala.txt'); becomes this: my $io = io('lalala.txt')->encoding('big5')->foobar; METHOD ROLE CALL Here is an alphabetical list of all the public methods that you can call on an IO::All object. "abs2rel", "absolute", "accept", "All", "all", "All_Dirs", "all_dirs", "All_Files", "all_files", "All_Links", "all_links", "append", "appendf", "appendln", "assert", "atime", "autoclose", "autoflush", "backwards", "bcc", "binary", "binmode", "blksize", "blocks", "block_size", "buffer", "canonpath", "case_tolerant", "catdir", "catfile", "catpath", "cc", "chdir", "chomp", "clear", "close", "confess", "content", "ctime", "curdir", "dbm", "deep", "device", "device_id", "devnull", "dir", "domain", "empty", "ext", "encoding", "eof", "errors", "file", "filename", "fileno", "filepath", "filter", "fork", "from", "ftp", "get", "getc", "getline", "getlines", "gid", "glob", "handle", "head", "http", "https", "inode", "io_handle", "is_absolute", "is_dir", "is_dbm", "is_executable", "is_file", "is_link", "is_mldbm", "is_open", "is_pipe", "is_readable", "is_socket", "is_stdio", "is_string", "is_temp", "is_writable", "join", "length", "link", "lock", "mailer", "mailto", "mimetype", "mkdir", "mkpath", "mldbm", "mode", "modes", "mtime", "name", "new", "next", "nlink", "open", "os" "password", "path", "pathname", "perms", "pipe", "port", "print", "printf", "println", "put", "rdonly", "rdwr", "read", "readdir", "readlink", "recv", "rel2abs", "relative", "rename", "request", "response", "rmdir", "rmtree", "rootdir", "scalar", "seek", "send", "separator", "shutdown", "size", "slurp", "socket", "sort", "splitdir", "splitpath", "stat", "stdio", "stderr", "stdin", "stdout", "string", "string_ref", "subject", "sysread", "syswrite", "tail", "tell", "temp", "tie", "tmpdir", "to", "touch", "truncate", "type", "user", "uid", "unlink", "unlock", "updir", "uri", "utf8", "utime" and "write". Each method is documented further below. OPERATOR OVERLOADING IO::All objects overload a small set of Perl operators to great effect. The overloads are limited to <, <<, >, >>, dereferencing operations, and stringification. Even though relatively few operations are overloaded, there is actually a huge matrix of possibilities for magic. That's because the overloading is sensitive to the types, position and context of the arguments, and an IO::All object can be one of many types. The most important overload to become familiar with is stringification. IO::All objects stringify to their file or directory name. Here we print the contents of the current directory: perl -MIO::All -le 'print for io(".")->all' is the same as: perl -MIO::All -le 'print $_->name for io(".")->all' Stringification is important because it allows IO::All operations to return objects when they might otherwise return file names. Then the recipient can use the result either as an object or a string. '>' and '<' move data between objects in the direction pointed to by the operator. $content1 < io('file1'); $content1 > io('file2'); io('file2') > $content3; io('file3') < $content3; io('file3') > io('file4'); io('file5') < io('file4'); '>>' and '<<' do the same thing except the recipient string or file is appended to. An IO::All file used as an array reference becomes tied using Tie::File: $file = io "file"; # Print last line of file print $file->[-1]; # Insert new line in middle of file $file->[$#$file / 2] = 'New line'; An IO::All file used as a hash reference becomes tied to a DBM class: io('mydbm')->{ingy} = 'YAML'; An IO::All directory used as an array reference, will expose each file or subdirectory as an element of the array. print "$_\n" for @{io 'dir'}; IO::All directories used as hash references have file names as keys, and IO::All objects as values: print io('dir')->{'foo.txt'}->slurp; Files used as scalar references get slurped: print ${io('dir')->{'foo.txt'}}; Not all combinations of operations and object types are supported. Some just haven't been added yet, and some just don't make sense. If you use an invalid combination, an error will be thrown. COOKBOOK This section describes some various things that you can easily cook up with IO::All. File Locking IO::All makes it very easy to lock files. Just use the "lock" method. Here's a standalone program that demonstrates locking for both write and read: use IO::All; my $io1 = io('myfile')->lock; $io1->println('line 1'); fork or do { my $io2 = io('myfile')->lock; print $io2->slurp; exit; }; sleep 1; $io1->println('line 2'); $io1->println('line 3'); $io1->unlock; There are a lot of subtle things going on here. An exclusive lock is issued for $io1 on the first "println". That's because the file isn't actually opened until the first IO operation. When the child process tries to read the file using $io2, there is a shared lock put on it. Since $io1 has the exclusive lock, the slurp blocks. The parent process sleeps just to make sure the child process gets a chance. The parent needs to call "unlock" or "close" to release the lock. If all goes well the child will print 3 lines. Round Robin This simple example will read lines from a file forever. When the last line is read, it will reopen the file and read the first one again. my $io = io 'file1.txt'; $io->autoclose(1); while (my $line = $io->getline || $io->getline) { print $line; } Reading Backwards If you call the "backwards" method on an IO::All object, the "getline" and "getlines" will work in reverse. They will read the lines in the file from the end to the beginning. my @reversed; my $io = io('file1.txt'); $io->backwards; while (my $line = $io->getline) { push @reversed, $line; } or more simply: my @reversed = io('file1.txt')->backwards->getlines; The "backwards" method returns the IO::All object so that you can chain the calls. NOTE: This operation requires that you have the File::ReadBackwards module installed. Client/Server Sockets IO::All makes it really easy to write a forking socket server and a client to talk to it. In this example, a server will return 3 lines of text, to every client that calls it. Here is the server code: use IO::All; my $socket = io(':12345')->fork->accept; $socket->print($_) while ; $socket->close; __DATA__ On your mark, Get set, Go! Here is the client code: use IO::All; my $io = io('localhost:12345'); print while $_ = $io->getline; You can run the server once, and then run the client repeatedly (in another terminal window). It should print the 3 data lines each time. Note that it is important to close the socket if the server is forking, or else the socket won't go out of scope and close. A Tiny Web Server Here is how you could write a simplistic web server that works with static and dynamic pages: perl -MIO::All -e 'io(":8080")->fork->accept->(sub { $_[0] < io(-x $1 ? "./$1 |" : $1) if /^GET \/(.*) / })' There is are a lot of subtle things going on here. First we accept a socket and fork the server. Then we overload the new socket as a code ref. This code ref takes one argument, another code ref, which is used as a callback. The callback is called once for every line read on the socket. The line is put into $_ and the socket itself is passed in to the callback. Our callback is scanning the line in $_ for an HTTP GET request. If one is found it parses the file name into $1. Then we use $1 to create an new IO::All file object... with a twist. If the file is executable ("-x"), then we create a piped command as our IO::All object. This somewhat approximates CGI support. Whatever the resulting object is, we direct the contents back at our socket which is in $_[0]. Pretty simple, eh? DBM Files IO::All file objects used as a hash reference, treat the file as a DBM tied to a hash. Here I write my DB record to STDERR: io("names.db")->{ingy} > io('='); Since their are several DBM formats available in Perl, IO::All picks the first one of these that is installed on your system: DB_File GDBM_File NDBM_File ODBM_File SDBM_File You can override which DBM you want for each IO::All object: my @keys = keys %{io('mydbm')->dbm('SDBM_File')}; File Subclassing Subclassing is easy with IO::All. Just create a new module and use IO::All as the base class, like this: package NewModule; use IO::All -base; You need to do it this way so that IO::All will export the "io" function. Here is a simple recipe for subclassing: IO::Dumper inherits everything from IO::All and adds an extra method called "dump", which will dump a data structure to the file we specify in the "io" function. Since it needs Data::Dumper to do the dumping, we override the "open" method to "require Data::Dumper" and then pass control to the real "open". First the code using the module: use IO::Dumper; io('./mydump')->dump($hash); And next the IO::Dumper module itself: package IO::Dumper; use IO::All -base; use Data::Dumper; sub dump { my $self = shift; Dumper(@_) > $self; } 1; Inline Subclassing This recipe does the same thing as the previous one, but without needing to write a separate module. The only real difference is the first line. Since you don't "use" IO::Dumper, you need to still call its "import" method manually. IO::Dumper->import; io('./mydump')->dump($hash); package IO::Dumper; use IO::All -base; use Data::Dumper; sub dump { my $self = shift; Dumper(@_) > $self; } THE IO::All METHODS This section gives a full description of all of the methods that you can call on IO::All objects. The methods have been grouped into subsections based on object construction, option settings, configuration, action methods and support for specific modules. Object Construction and Initialization Methods * new There are three ways to create a new IO::All object. The first is with the special function "io" which really just calls "IO::All->new". The second is by calling "new" as a class method. The third is calling "new" as an object instance method. In this final case, the new objects attributes are copied from the instance object. io(file-descriptor); IO::All->new(file-descriptor); $io->new(file-descriptor); All three forms take a single argument, a file descriptor. A file descriptor can be any of the following: - A file name - A file handle - A directory name - A directory handle - A typeglob reference - A piped shell command. eq '| ls -al' - A socket domain/port. eg 'perl.com:5678' - '-' means STDIN or STDOUT (depending on usage) - '=' means STDERR - '$' means an IO::String object - '?' means a temporary file - A URI including: http, https, ftp and mailto - An IO::All object If you provide an IO::All object, you will simply get that *same object* returned from the constructor. If no file descriptor is provided, an object will still be created, but it must be defined by one of the following methods before it can be used for I/O: * file io->file("path/to/my/file.txt"); Using the "file" method sets the type of the object to *file* and sets the pathname of the file if provided. It might be important to use this method if you had a file whose name was '-', or if the name might otherwise be confused with a directory or a socket. In this case, either of these statements would work the same: my $file = io('-')->file; my $file = io->file('-'); * dir io->dir($dir_name); Make the object be of type *directory*. * socket io->socket("${domain}:${port}"); Make the object be of type *socket*. * link io->link($link_name); Make the object be of type *link*. * pipe io->pipe($pipe_command); Make the object be of type *pipe*. The following two statements are equivalent: my $io = io('ls -l |'); my $io = io('ls -l')->pipe; my $io = io->pipe('ls -l'); * dbm This method takes the names of zero or more DBM modules. The first one that is available is used to process the dbm file. io('mydbm')->dbm('NDBM_File', 'SDBM_File')->{author} = 'ingy'; If no module names are provided, the first available of the following is used: DB_File GDBM_File NDBM_File ODBM_File SDBM_File * mldbm Similar to the "dbm" method, except create a Multi Level DBM object using the MLDBM module. This method takes the names of zero or more DBM modules and an optional serialization module. The first DBM module that is available is used to process the MLDBM file. The serialization module can be Data::Dumper, Storable or FreezeThaw. io('mymldbm')->mldbm('GDBM_File', 'Storable')->{author} = {nickname => 'ingy'}; * string Make the object be an IO::String object. These are equivalent: my $io = io('$'); my $io = io->string; * temp Make the object represent a temporary file. It will automatically be open for both read and write. * stdio Make the object represent either STDIN or STDOUT depending on how it is used subsequently. These are equivalent: my $io = io('-'); my $io = io->stdin; * stdin Make the object represent STDIN. * stdout Make the object represent STDOUT. * stderr Make the object represent STDERR. * handle io->handle($io_handle); Forces the object to be created from an pre-existing IO handle. You can chain calls together to indicate the type of handle: my $file_object = io->file->handle($file_handle); my $dir_object = io->dir->handle($dir_handle); * http Make the object represent an HTTP URI. Requires IO-All-LWP. * https Make the object represent an HTTPS URI. Requires IO-All-LWP. * ftp Make the object represent an FTP URI. Requires IO-All-LWP. * mailto Make the object represent a "mailto:" URI. Requires IO-All-Mailto. If you need to use the same options to create a lot of objects, and don't want to duplicate the code, just create a dummy object with the options you want, and use that object to spawn other objects. my $lt = io->lock->tie; ... my $io1 = $lt->new('file1'); my $io2 = $lt->new('file2'); Since the new method copies attributes from the calling object, both $io1 and $io2 will be locked and tied. Option Setting Methods The following methods don't do any actual I/O, but they specify options about how the I/O should be done. Each option can take a single argument of 0 or 1. If no argument is given, the value 1 is assumed. Passing 0 turns the option off. All of these options return the object reference that was used to invoke them. This is so that the option methods can be chained together. For example: my $io = io('path/file')->tie->assert->chomp->lock; * absolute Indicates that the "pathname" for the object should be made absolute. # Print the full path of the current working directory # (like pwd). use IO::All; print io->curdir->absolute; * assert This method ensures that the path for a file or directory actually exists before the file is open. If the path does not exist, it is created. For example, here is a program called "create-cat-to" that outputs to a file that it creates. #!/usr/bin/perl # create-cat-to.pl # cat to a file that can be created. use strict; use warnings; use IO::All; my $filename = shift(@ARGV); # Create a file called $filename, including all leading components. io('-') > io->file($filename)->assert; Here's an example use of it: $ ls -l total 0 $ echo "Hello World" | create-cat-to one/two/three/four.txt $ ls -l total 4 drwxr-xr-x 3 shlomif shlomif 4096 2010-10-14 18:03 one/ $ cat one/two/three/four.txt Hello World $ * autoclose By default, IO::All will close an object opened for input when EOF is reached. By closing the handle early, one can immediately do other operations on the object without first having to close it. This option is on by default, so if you don't want this behaviour, say so like this: $io->autoclose(0); The object will then be closed when $io goes out of scope, or you manually call "$io->close". * autoflush Proxy for IO::Handle::autoflush * backwards Sets the object to 'backwards' mode. All subsequent "getline" operations will read backwards from the end of the file. Requires the File::ReadBackwards CPAN module. * binary Indicates the file has binary content and should be opened with "binmode". * chdir chdir() to the pathname of a directory object. When object goes out of scope, chdir back to starting directory. * chomp Indicates that all operations that read lines should chomp the lines. If the "separator" method has been called, chomp will remove that value from the end of each record. * confess Errors should be reported with the very detailed Carp::confess function. * deep Indicates that calls to the "all" family of methods should search directories as deep as possible. * fork Indicates that the process should automatically be forked inside the "accept" socket method. * lock Indicate that operations on an object should be locked using flock. * rdonly This option indicates that certain operations like DBM and Tie::File access should be done in read-only mode. * rdwr This option indicates that DBM and MLDBM files should be opened in read- write mode. * relative Indicates that the "pathname" for the object should be made relative. * sort Indicates whether objects returned from one of the "all" methods will be in sorted order by name. True by default. * tie Indicate that the object should be tied to itself, thus allowing it to be used as a filehandle in any of Perl's builtin IO operations. my $io = io('foo')->tie; @lines = <$io>; * utf8 Indicates that IO should be done using utf8 encoding. Calls binmode with ":utf8" layer. Configuration Methods The following methods don't do any actual I/O, but they set specific values to configure the IO::All object. If these methods are passed no argument, they will return their current value. If arguments are passed they will be used to set the current value, and the object reference will be returned for potential method chaining. * bcc Set the Bcc field for a mailto object. * binmode Proxy for binmode. Requires a layer to be passed. Use "binary" for plain binary mode. * block_size The default length to be used for "read" and "sysread" calls. Defaults to 1024. * buffer Returns a reference to the internal buffer, which is a scalar. You can use this method to set the buffer to a scalar of your choice. (You can just pass in the scalar, rather than a reference to it.) This is the buffer that "read" and "write" will use by default. You can easily have IO::All objects use the same buffer: my $input = io('abc'); my $output = io('xyz'); my $buffer; $output->buffer($input->buffer($buffer)); $output->write while $input->read; * cc Set the Cc field for a mailto object. * content Get or set the content for an LWP operation manually. * domain Set the domain name or ip address that a socket should use. * encoding Set the encoding to be used for the PerlIO layer. * errors Use this to set a subroutine reference that gets called when an internal error is thrown. * filter Use this to set a subroutine reference that will be used to grep which objects get returned on a call to one of the "all" methods. For example: my @odd = io->curdir->filter(sub {$_->size % 2})->All_Files; @odd will contain all the files under the current directory whose size is an odd number of bytes. * from Indicate the sender for a mailto object. * mailer Set the mailer program for a mailto transaction. Defaults to 'sendmail'. * mode Set the mode for which the file should be opened. Examples: $io->mode('>>')->open; $io->mode(O_RDONLY); my $log_appender = io->file('/var/log/my-application.log') ->mode('>>')->open(); $log_appender->print("Stardate 5987.6: Mission accomplished."); * name Set or get the name of the file or directory represented by the IO::All object. * password Set the password for an LWP transaction. * perms Sets the permissions to be used if the file/directory needs to be created. * port Set the port number that a socket should use. * request Manually specify the request object for an LWP transaction. * response Returns the resulting response object from an LWP transaction. * separator Sets the record (line) separator to whatever value you pass it. Default is \n. Affects the chomp setting too. * string_ref Proxy for IO::String::string_ref Returns a reference to the internal string that is acting like a file. * subject Set the subject for a mailto transaction. * to Set the recipient address for a mailto request. * uri Direct access to the URI used in LWP transactions. * user Set the user name for an LWP transaction. IO Action Methods These are the methods that actually perform I/O operations on an IO::All object. The stat methods and the File::Spec methods are documented in separate sections below. * accept For sockets. Opens a server socket (LISTEN => 1, REUSE => 1). Returns an IO::All socket object that you are listening on. If the "fork" method was called on the object, the process will automatically be forked for every connection. * all Read all contents into a single string. compare(io('file1')->all, io('file2')->all); * all (For directories) Returns a list of IO::All objects for all files and subdirectories in a directory. '.' and '..' are excluded. Takes an optional argument telling how many directories deep to search. The default is 1. Zero (0) means search as deep as possible. The filter method can be used to limit the results. The items returned are sorted by name unless "->sort(0)" is used. * All Same as all(0). * all_dirs Same as "all", but only return directories. * All_Dirs Same as all_dirs(0). * all_files Same as "all", but only return files. * All_Files Same as all_files(0). * all_links Same as "all", but only return links. * All_Links Same as all_links(0). * append Same as print, but sets the file mode to '>>'. * appendf Same as printf, but sets the file mode to '>>'. * appendln Same as println, but sets the file mode to '>>'. * clear Clear the internal buffer. This method is called by "write" after it writes the buffer. Returns the object reference for chaining. * close Close will basically unopen the object, which has different meanings for different objects. For files and directories it will close and release the handle. For sockets it calls shutdown. For tied things it unties them, and it unlocks locked things. * empty Returns true if a file exists but has no size, or if a directory exists but has no contents. * eof Proxy for IO::Handle::eof * ext Returns the extension of the file. Can also be spelled as "extension" * exists Returns whether or not the file or directory exists. * filename Return the name portion of the file path in the object. For example: io('my/path/file.txt')->filename; would return "file.txt". * fileno Proxy for IO::Handle::fileno * filepath Return the path portion of the file path in the object. For example: io('my/path/file.txt')->filepath; would return "my/path". * get Perform an LWP GET request manually. * getc Proxy for IO::Handle::getc * getline Calls IO::File::getline. You can pass in an optional record separator. * getlines Calls IO::File::getlines. You can pass in an optional record separator. * glob Creates IO::All objects for the files matching the glob in the IO::All::Dir. For example: io->dir($ENV{HOME})->glob('*.txt') * head Return the first 10 lines of a file. Takes an optional argument which is the number of lines to return. Works as expected in list and scalar context. Is subject to the current line separator. * io_handle Direct access to the actual IO::Handle object being used on an opened IO::All object. * is_dir Returns boolean telling whether or not the IO::All object represents a directory. * is_executable Returns true if file or directory is executable. * is_dbm Returns boolean telling whether or not the IO::All object represents a dbm file. * is_file Returns boolean telling whether or not the IO::All object represents a file. * is_link Returns boolean telling whether or not the IO::All object represents a symlink. * is_mldbm Returns boolean telling whether or not the IO::All object represents a mldbm file. * is_open Indicates whether the IO::All is currently open for input/output. * is_pipe Returns boolean telling whether or not the IO::All object represents a pipe operation. * is_readable Returns true if file or directory is readable. * is_socket Returns boolean telling whether or not the IO::All object represents a socket. * is_stdio Returns boolean telling whether or not the IO::All object represents a STDIO file handle. * is_string Returns boolean telling whether or not the IO::All object represents an IO::String object. * is_temp Returns boolean telling whether or not the IO::All object represents a temporary file. * is_writable Returns true if file or directory is writable. Can also be spelled as "is_writeable". * length Return the length of the internal buffer. * mimetype Return the mimetype of the file. Requires a working installation of the File::MimeInfo CPAN module. * mkdir Create the directory represented by the object. * mkpath Create the directory represented by the object, when the path contains more than one directory that doesn't exist. Proxy for File::Path::mkpath. * next For a directory, this will return a new IO::All object for each file or subdirectory in the directory. Return undef on EOD. * open Open the IO::All object. Takes two optional arguments "mode" and "perms", which can also be set ahead of time using the "mode" and "perms" methods. NOTE: Normally you won't need to call open (or mode/perms), since this happens automatically for most operations. * os Change the object's os representation. Valid options are: "win32", "unix", "vms", "mac", "os2". * pathname Return the absolute or relative pathname for a file or directory, depending on whether object is in "absolute" or "relative" mode. * print Proxy for IO::Handle::print * printf Proxy for IO::Handle::printf * println Same as print, but adds newline to each argument unless it already ends with one. * put Perform an LWP PUT request manually. * read This method varies depending on its context. Read carefully (no pun intended). For a file, this will proxy IO::File::read. This means you must pass it a buffer, a length to read, and optionally a buffer offset for where to put the data that is read. The function returns the length actually read (which is zero at EOF). If you don't pass any arguments for a file, IO::All will use its own internal buffer, a default length, and the offset will always point at the end of the buffer. The buffer can be accessed with the "buffer" method. The length can be set with the "block_size" method. The default length is 1024 bytes. The "clear" method can be called to clear the buffer. For a directory, this will proxy IO::Dir::read. * readdir Similar to the Perl "readdir" builtin. In scalar context, return the next directory entry (ie file or directory name), or undef on end of directory. In list context, return all directory entries. Note that "readdir" does not return the special "." and ".." entries. * readline Same as "getline". * readlink Calls Perl's readlink function on the link represented by the object. Instead of returning the file path, it returns a new IO::All object using the file path. * recv Proxy for IO::Socket::recv * rename my $new = $io->rename('new-name'); Calls Perl's rename function and returns an IO::All object for the renamed file. Returns false if the rename failed. * rewind Proxy for IO::Dir::rewind * rmdir Delete the directory represented by the IO::All object. * rmtree Delete the directory represented by the IO::All object and all the files and directories beneath it. Proxy for File::Path::rmtree. * scalar Deprecated. Same as "all()". * seek Proxy for IO::Handle::seek. If you use seek on an unopened file, it will be opened for both read and write. * send Proxy for IO::Socket::send * shutdown Proxy for IO::Socket::shutdown * slurp Read all file content in one operation. Returns the file content as a string. In list context returns every line in the file. * stat Proxy for IO::Handle::stat * sysread Proxy for IO::Handle::sysread * syswrite Proxy for IO::Handle::syswrite * tail Return the last 10 lines of a file. Takes an optional argument which is the number of lines to return. Works as expected in list and scalar context. Is subject to the current line separator. * tell Proxy for IO::Handle::tell * throw This is an internal method that gets called whenever there is an error. It could be useful to override it in a subclass, to provide more control in error handling. * touch Update the atime and mtime values for a file or directory. Creates an empty file if the file does not exist. * truncate Proxy for IO::Handle::truncate * type Returns a string indicated the type of io object. Possible values are: file dir link socket string pipe Returns undef if type is not determinable. * unlink Unlink (delete) the file represented by the IO::All object. NOTE: You can unlink a file after it is open, and continue using it until it is closed. * unlock Release a lock from an object that used the "lock" method. * utime Proxy for the utime Perl function. * write Opposite of "read" for file operations only. NOTE: When used with the automatic internal buffer, "write" will clear the buffer after writing it. Stat Methods This methods get individual values from a stat call on the file, directory or handle represented by the IO::All object. * atime Last access time in seconds since the epoch * blksize Preferred block size for file system I/O * blocks Actual number of blocks allocated * ctime Inode change time in seconds since the epoch * device Device number of filesystem * device_id Device identifier for special files only * gid Numeric group id of file's owner * inode Inode number * modes File mode - type and permissions * mtime Last modify time in seconds since the epoch * nlink Number of hard links to the file * size Total size of file in bytes * uid Numeric user id of file's owner File::Spec Methods These methods are all adaptations from File::Spec. Each method actually does call the matching File::Spec method, but the arguments and return values differ slightly. Instead of being file and directory names, they are IO::All objects. Since IO::All objects stringify to their names, you can generally use the methods just like File::Spec. * abs2rel Returns the relative path for the absolute path in the IO::All object. Can take an optional argument indicating the base path. * canonpath Returns the canonical path for the IO::All object. * case_tolerant Returns 0 or 1 indicating whether the file system is case tolerant. Since an active IO::All object is not needed for this function, you can code it like: IO::All->case_tolerant; or more simply: io->case_tolerant; * catdir Concatenate the directory components together, and return a new IO::All object representing the resulting directory. * catfile Concatenate the directory and file components together, and return a new IO::All object representing the resulting file. my $contents = io->catfile(qw(dir subdir file))->slurp; This is a very portable way to read "dir/subdir/file". * catpath Concatenate the volume, directory and file components together, and return a new IO::All object representing the resulting file. * curdir Returns an IO::All object representing the current directory. * devnull Returns an IO::All object representing the /dev/null file. * is_absolute Returns 0 or 1 indicating whether the "name" field of the IO::All object is an absolute path. * join Same as "catfile". * path Returns a list of IO::All directory objects for each directory in your path. * rel2abs Returns the absolute path for the relative path in the IO::All object. Can take an optional argument indicating the base path. * rootdir Returns an IO::All object representing the root directory on your file system. * splitdir Returns a list of the directory components of a path in an IO::All object. * splitpath Returns a volume directory and file component of a path in an IO::All object. * tmpdir Returns an IO::All object representing a temporary directory on your file system. * updir Returns an IO::All object representing the current parent directory. OPERATIONAL NOTES * Each IO::All object gets reblessed into an IO::All::* object as soon as IO::All can determine what type of object it should be. Sometimes it gets reblessed more than once: my $io = io('mydbm.db'); $io->dbm('DB_File'); $io->{foo} = 'bar'; In the first statement, $io has a reference value of 'IO::All::File', if "mydbm.db" exists. In the second statement, the object is reblessed into class 'IO::All::DBM'. * An IO::All object will automatically be opened as soon as there is enough contextual information to know what type of object it is, and what mode it should be opened for. This is usually when the first read or write operation is invoked but might be sooner. * The mode for an object to be opened with is determined heuristically unless specified explicitly. * For input, IO::All objects will automatically be closed after EOF (or EOD). For output, the object closes when it goes out of scope. To keep input objects from closing at EOF, do this: $io->autoclose(0); * You can always call "open" and "close" explicitly, if you need that level of control. To test if an object is currently open, use the "is_open" method. * Overloaded operations return the target object, if one exists. This would set $xxx to the IO::All object: my $xxx = $contents > io('file.txt'); While this would set $xxx to the content string: my $xxx = $contents < io('file.txt'); STABILITY The goal of the IO::All project is to continually refine the module to be as simple and consistent to use as possible. Therefore, in the early stages of the project, I will not hesitate to break backwards compatibility with other versions of IO::All if I can find an easier and clearer way to do a particular thing. IO is tricky stuff. There is definitely more work to be done. On the other hand, this module relies heavily on very stable existing IO modules; so it may work fairly well. I am sure you will find many unexpected "features". Please send all problems, ideas and suggestions to ingy@cpan.org. Known Bugs and Deficiencies Not all possible combinations of objects and methods have been tested. There are many many combinations. All of the examples have been tested. If you find a bug with a particular combination of calls, let me know. If you call a method that does not make sense for a particular object, the result probably won't make sense. Little attempt is made to check for improper usage. SEE ALSO IO::Handle, IO::File, IO::Dir, IO::Socket, IO::String, File::Spec, File::Path, File::ReadBackwards, Tie::File, File::MimeInfo CREDITS A lot of people have sent in suggestions, that have become a part of IO::All. Thank you. Special thanks to Ian Langworth for continued testing and patching. Thank you Simon Cozens for tipping me off to the overloading possibilities. Finally, thanks to Autrijus Tang, for always having one more good idea. (It seems IO::All of it to a lot of people!) REPOSITORY AND COMMUNITY The IO::All module can be found on CPAN and on GitHub: . Please join the IO::All discussion on #io-all on irc.perl.org. AUTHOR Ingy döt Net COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008, 2010. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See Changes100644001750001750 1500112267312543 13146 0ustar00frewfrew000000000000IO-All-0.54--- version: 0.54 hanges: - Remove mentions of unimplemented strict (Thanks Mithlandu, GH#15) - Allow testing on non SDBM DBM's (thanks Jerry D. Hedden) - Abandon RT in favor of GitHub Issues --- version: 0.53 changes: - Make mkdir die if it fails (thanks Martyn Pearce for RT#61697) - Fix possible path test issues, esp in Win32 (Thanks Mithlandu) - Fix ->binary under -utf8 import mode (thanks T. Linden for RT#81224) - Validate UTF-8 in ->utf8 (thanks Ovid for RT#74642) - Consistently use :encoding($encoding) (thanks Bernardo Rechea for RT#68512) - Pass perms to mkpath in assert_dirpath (thanks Rob Kinyon for RT#53687) - Fix minor POD niggle (thanks Greg Skyles for RT#83798) - Remove broken test for ->mimetype (thanks Slaven Rezić for RT#91743) - Skip t/encoding.t for perls built without PerlIO::encoding (thanks Jerry D. Hedden for RT#26230) --- version: 0.52 changes: - Add a fix for io->file("foobar")->assert (Shlomi Fish) - Make io->file('') not break on Windows systems (Roy Ivy III) - Fix dangling file handles in tests (Roy Ivy III) --- version: 0.51 date: Mon Dec 30 13:55:00 CDT 2013 changes: - Make '' not become / when using io->dir('') --- version: 0.50 date: Fri Oct 18 13:08:41 PDT 2013 changes: - Fix for rt87200 --- version: 0.49 date: Fri Oct 18 01:05:39 CDT 2013 changes: - Fix various tests on Windows --- version: 0.48 date: Tue Oct 8 01:45:39 CDT 2013 changes: - Add ->os method to ::Filesys (Arthur Axel "fREW" Schmidt) --- version: 0.47 date: Mon Sep 30 18:57:52 CDT 2013 changes: - Add ->glob method to ::Dir (Arthur Axel "fREW" Schmidt) - Add list based constructors to ::Dir and ::File (Arthur Axel "fREW" Schmidt) - Add ->mimetype method to ::FileSys (Arthur Axel "fREW" Schmidt) - Add ->ext method to ::FileSys (Arthur Axel "fREW" Schmidt) - All tests should be parallelizable (Shlomi Fish) --- version: 0.46 date: Wed Jul 25 17:35:44 PDT 2012 changes: - Re-releasing to reclaim indexing from Alt-IO-All-new --- version: 0.45 date: Wed Jul 18 22:15:04 EDT 2012 changes: - Added an example for ->assert and fixed the \E warnings on 5.16, courtesy shlomi fish --- version: 0.44 date: Wed Oct 5 18:11:27 EDT 2011 changes: - Switch from testing $^V to $^] in DESTROY since $^V comparisons leak pre-5.14 (mst) --- version: 0.43 date: Wed Jul 20 08:34:01 PDT 2011 changes: - Fix directory scalar deref for mst++ --- version: 0.42 date: Mon Jul 18 11:31:43 PDT 2011 changes: - Doc work and tests by Shlomi Fish - Use Module::Package - Fix rt41819 --- version: 0.41 date: Mon Aug 16 22:33:45 PDT 2010 changes: - Recent Test::More was triggering errors in file_spec.t. - Thanks to Torsten Raudssus for a fix. Getty++ --- version: 0.40 date: Sun Aug 15 15:22:12 PDT 2010 changes: - Fixed a bug in t/chdir.t --- version: 0.39 date: Thu Dec 11 23:22:56 PST 2008 changes: - Fix tests on 5.6. --- version: 0.38 date: Mon Apr 9 10:52:44 JST 2007 changes: - Add generic encoding, instead of just utf8. --- version: 0.37 date: Fri Apr 6 18:04:27 JST 2007 changes: - make catdir work with current dir in addition to other args. - make catfile work with current dir in addition to other args. - Add support for import flags like -strict and -utf8 --- version: 0.36 date: Mon Oct 16 14:48:58 PDT 2006 changes: - Applied the patch from http://rt.cpan.org/Public/Bug/Display.html?id=20053 Made sure Carp is required and the sub Carp::carp is predeclared in IO/All.pm. --- version: 0.35 date: Tue May 9 08:25:37 PDT 2006 changes: - Remove dependency on XXX.pm *groan* --- version: 0.34 date: Mon May 8 01:03:12 PDT 2006 changes: - Remove dependency on Spiffy.pm - Apply patches and fix bugs from rt - rt tickets - 11552 12048 14184 12966 13879 17105 7448 11463 7410 7337 7527 18465 --- version: 0.33 date: Fri Dec 17 02:33:41 PST 2004 changes: - Fixed some nagging problems with the tests --- version: 0.32 date: Wed Dec 15 12:19:44 PST 2004 changes: - io('path/to/symlink') would return a file object if the link was to a file. (Dave Rolsky) - $link->readlink incorrectly returned a new IO::All::Link object, no matter what the link pointed to. (Dave Rolsky) - io($io_all_object) would not return an object of the same type as the object give to io(), it would always return a plain IO::All object. (Dave Rolsky) - add head and tail methods --- version: 0.31 date: Sun Aug 8 22:49:46 PDT 2004 changes: - added readdir - let exists work on non-existant filename --- version: 0.31 date: Sat Jul 24 20:19:10 PDT 2004 changes: - absolute, relative, pathname - chdir - stat on unopened file/dir --- version: 0.30 date: Mon Jul 19 11:23:15 PDT 2004 changes: - Split module into several classes - Pluggable framework - file->all - ->touch - ->empty --- version: 0.22 date: Tue Jun 1 11:20:17 PDT 2004 changes: - Make tests pass on MSWin32 :P - Added exists method --- version: 0.21 date: Sat May 29 12:45:00 PDT 2004 changes: - Fixed buglets in sockets - Added Cookbook example for Tiny Web Server --- version: 0.20 date: Thu May 27 01:46:04 PDT 2004 changes: - Rewrote documentation - Refactored construction - File::Spec support - File::Path support - lots of new methods --- version: 0.20 date: Mon May 24 17:02:24 PDT 2004 changes: - DBM support - MLDBM support - chomp support - Fixed forking server zombie issues - Replaced flags with methods (-tie -fork -lock, etc) - Added chainable options: assert, chomp, deep, rdonly, rdwr, sort - Fixed problems with perl-5.6.1 and Solaris --- version: 0.18 date: Sun May 16 17:40:37 PDT 2004 changes: - Get the shift out - Support DBM files as has overload - Add ->scalar() method - close orphaned socket on fork after accept - seek now opens file for read/write - polish subtle behaviour - added stat functions --- version: 0.17 date: Fri May 7 01:14:36 PDT 2004 changes: - File to File copy use File::Copy for speed --- version: 0.16 date: Mon Mar 22 23:35:32 PST 2004 changes: - Added tests for some subtleties - Added check_nmake to Makefile.PL --- version: 0.15 date: Mon Mar 15 09:50:46 PST 2004 changes: - Got things working on MSWin32 - turned off lock.t on solaris and cygwin for now --- version: 0.14 date: Mon Mar 15 00:19:21 PST 2004 changes: - Added multiple dispatch overloading - Added Tie::File support --- version: 0.13 date: Fri Mar 12 00:02:10 PST 2004 changes: - Accidentally left debugging code in module. --- version: 0.12 date: Tue Mar 2 21:50:05 PST 2004 changes: - Require IO::String --- version: 0.11 date: Tue Mar 2 09:21:39 PST 2004 changes: - Depend on newer Spiffy --- version: 0.10 date: Sat Feb 7 00:55:42 PST 2004 changes: - Initial release. new.t100644001750001750 101112267312543 13050 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 4; use IO::All; use IO_All_Test; my $filename = f 't/mydir/file1'; my $file = io($filename); ok($file->isa('IO::All::File'), 'string passed to io() is returned as a file'); is($file->name, $filename, 'name() is the same as the string'); my $file2 = io($file); ok($file2->isa('IO::All::File'), 'IO::All::File object passed to io() is returned as a file'); is($file2->name, $filename, 'name() is the same as the original string'); del_output_dir(); xxx.t100644001750001750 56512267312543 13103 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 1; use IO::All; use IO::All::Temp; use IO::All::String; use IO::All::Socket; use IO::All::MLDBM; use IO::All::Link; use IO::All::Pipe; use IO::All::Dir; use IO::All::Filesys; use IO::All::File; use IO::All::DBM; use IO::All::STDIO; use IO::All::Base; is($INC{'XXX.pm'}, undef, "Don't ship with XXX"); all.t100644001750001750 572712267312543 13051 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 30; use IO::All; use IO_All_Test; my $expected1 = 't/mydir/dir1;t/mydir/dir2;t/mydir/file1;t/mydir/file2;t/mydir/file3'; my $expected2 = 't/mydir/dir1;t/mydir/dir1/dira;t/mydir/dir1/file1;t/mydir/dir2;t/mydir/dir2/file1;t/mydir/file1;t/mydir/file2;t/mydir/file3'; my $expected3 = 't/mydir/dir1;t/mydir/dir1/dira;t/mydir/dir1/dira/dirx;t/mydir/dir1/file1;t/mydir/dir2;t/mydir/dir2/file1;t/mydir/file1;t/mydir/file2;t/mydir/file3'; my $expected4 = 't/mydir/dir1;t/mydir/dir1/dira;t/mydir/dir1/dira/dirx;t/mydir/dir1/dira/dirx/file1;t/mydir/dir1/file1;t/mydir/dir2;t/mydir/dir2/file1;t/mydir/file1;t/mydir/file2;t/mydir/file3'; my $expected_files1 = 't/mydir/file1;t/mydir/file2;t/mydir/file3'; my $expected_files2 = 't/mydir/dir1/file1;t/mydir/dir2/file1;t/mydir/file1;t/mydir/file2;t/mydir/file3'; my $expected_files4 = 't/mydir/dir1/dira/dirx/file1;t/mydir/dir1/file1;t/mydir/dir2/file1;t/mydir/file1;t/mydir/file2;t/mydir/file3'; my $expected_dirs1 = 't/mydir/dir1;t/mydir/dir2'; my $expected_dirs2 = 't/mydir/dir1;t/mydir/dir1/dira;t/mydir/dir2'; my $expected_dirs3 = 't/mydir/dir1;t/mydir/dir1/dira;t/mydir/dir1/dira/dirx;t/mydir/dir2'; my $expected_filt1 = 't/mydir/dir1/dira;t/mydir/dir1/dira/dirx'; my $expected_filt2 = 't/mydir/dir1/dira/dirx'; sub prep { join ';', grep { not /CVS|\.svn/ } @_ } is(prep(io('t/mydir')->all), f$expected1); is(prep(io('t/mydir')->all(1)), f$expected1); is(prep(io('t/mydir')->all(2)), f$expected2); is(prep(io('t/mydir')->all(3)), f$expected3); is(prep(io('t/mydir')->all(4)), f$expected4); is(prep(io('t/mydir')->all(5)), f$expected4); is(prep(io('t/mydir')->all(0)), f$expected4); is(prep(io('t/mydir')->All), f$expected4); is(prep(io('t/mydir')->deep->all), f$expected4); is(prep(io('t/mydir')->all_files), f$expected_files1); is(prep(io('t/mydir')->all_files(1)), f$expected_files1); is(prep(io('t/mydir')->all_files(2)), f$expected_files2); is(prep(io('t/mydir')->all_files(3)), f$expected_files2); is(prep(io('t/mydir')->all_files(4)), f$expected_files4); is(prep(io('t/mydir')->all_files(5)), f$expected_files4); is(prep(io('t/mydir')->all_files(0)), f$expected_files4); is(prep(io('t/mydir')->All_Files), f$expected_files4); is(prep(io('t/mydir')->deep->all_files), f$expected_files4); is(prep(io('t/mydir')->All_Files(2)), f$expected_files4); is(prep(io('t/mydir')->all_dirs), f$expected_dirs1); is(prep(io('t/mydir')->all_dirs(1)), f$expected_dirs1); is(prep(io('t/mydir')->all_dirs(2)), f$expected_dirs2); is(prep(io('t/mydir')->all_dirs(3)), f$expected_dirs3); is(prep(io('t/mydir')->all_dirs(4)), f$expected_dirs3); is(prep(io('t/mydir')->all_dirs(5)), f$expected_dirs3); is(prep(io('t/mydir')->all_dirs(0)), f$expected_dirs3); is(prep(io('t/mydir')->All_Dirs), f$expected_dirs3); is(prep(io('t/mydir')->deep->all_dirs), f$expected_dirs3); is(prep(io('t/mydir')->filter(sub {/dira/})->All_Dirs), f$expected_filt1); is(prep(io('t/mydir')->filter(sub {/x/})->All_Dirs), f$expected_filt2); del_output_dir(); tie.t100644001750001750 33112267312543 13024 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 1; use IO::All; use IO_All_Test; my $io = io('t/tie.t')->tie; my $file = join '', <$io>; test_file_contents($file, 't/tie.t'); del_output_dir(); dbm.t100644001750001750 112312267312543 13025 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; my $db_file; BEGIN { use Config; foreach (qw/SDBM_File GDBM_File ODBM_File NDBM_File DB_File/) { if ($Config{extensions} =~ /\b$_\b/) { $db_file = $_; last; } } } use Test::More defined($db_file) ? (tests => 2) : (skip_all => 'No DMB modules available'); use IO::All; use IO_All_Test; { my $db = io(o_dir() . '/mydbm')->dbm($db_file); $db->{fortytwo} = 42; $db->{foo} = 'bar'; is(join('', sort keys %$db), 'foofortytwo'); is(join('', sort values %$db), '42bar'); } del_output_dir(); LICENSE100644001750001750 4365612267312543 12701 0ustar00frewfrew000000000000IO-All-0.54This software is copyright (c) 2014 by Ingy döt Net. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2014 by Ingy döt Net. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Suite 500, Boston, MA 02110-1335 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2014 by Ingy döt Net. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End dist.ini100644001750001750 52612267312543 13265 0ustar00frewfrew000000000000IO-All-0.54name = IO-All author = Ingy döt Net license = Perl_5 copyright_holder = Ingy döt Net version = 0.54 [NextRelease] [@Git] [@Basic] [GithubMeta] user = ingydotnet issues = 1 [MetaJSON] [OurPkgVersion] [ReadmeFromPod] filename = lib/IO/All.pod [PodSyntaxTests] [Prereqs::FromCPANfile] cpanfile100644001750001750 10112267312543 13312 0ustar00frewfrew000000000000IO-All-0.54requires 'IO::String' => 1.08; recommends 'File::ReadBackwards'; all2.t100644001750001750 36412267312543 13103 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 2; use IO::All; use IO_All_Test; test_file_contents(io->file('t/all2.t')->all, 't/all2.t'); test_file_contents(io->file('t/all2.t')->scalar, 't/all2.t'); del_output_dir(); link.t100644001750001750 215212267312543 13223 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More; use IO::All; use IO_All_Test; use Cwd qw(abs_path); my $cwd = abs_path('.'); eval { symlink("$cwd/lib/IO/All.pm", o_dir() . '/IO-All-file-link') or die $! }; if ($@ or not (-e o_dir() . '/IO-All-file-link' and -l o_dir() . '/IO-All-file-link')) { plan skip_all => 'Cannot call symlink on this platform'; } else { plan tests => 7; } my $file_link = io(o_dir() . '/IO-All-file-link'); ok($file_link->is_link, 'Link to file is a link (not a file)'); my $file_target = $file_link->readlink; ok(! $file_target->is_link, 'readlink returns file object, not link' ); is($file_target->filename, 'All.pm', 'link target is expected file' ); symlink("$cwd/lib/IO", o_dir() . '/IO-All-dir-link'); my $dir_link = io(o_dir() . '/IO-All-dir-link'); ok($dir_link->is_link, 'Link to dir is a link (not a dir)'); my $dir_target = $dir_link->readlink; ok(! $dir_target->is_link, 'readlink returns dir object, not link' ); ok($dir_target->is_dir, 'readlink returns dir object, not link' ); is($dir_target->filename, 'IO', 'link target is expected dir' ); del_output_dir(); seek.t100644001750001750 44312267312543 13176 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 1; use IO::All; use IO_All_Test; { my $string < (io('t/mystuff') > io(o_dir() . '/seek')); my $io = io(o_dir() . '/seek'); $io->seek(index($string, 'quite'), 0); is($io->getline, "quite enough.\n"); } del_output_dir(); pipe.t100644001750001750 46112267312543 13204 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 4; use IO::All; my $perl_version < io('perl -v|'); ok($perl_version =~ /Larry Wall/); ok($perl_version =~ /This is perl/); io("$^X -v|") > $perl_version; ok($perl_version =~ /Larry Wall/); ok($perl_version =~ /This is p(erl|onie)/); lock.t100755001750001750 114212267312543 13217 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use IO::All; use IO_All_Test; # XXX This needs to be fixed!!! $^O !~ /^(cygwin|hpux)$/ ? print "1..3\n" : do { print "1..0 # skip - locking problems on $^O\n"; exit(0) }; { my $io1 = io(o_dir() . '/foo')->lock; $io1->println('line 1'); my $pid; ($pid = fork) or do { my $io2 = io(o_dir() . '/foo')->lock; foreach (1 .. 3) { print "not " unless($io2->getline eq "line $_\n"); print "ok $_\n"; } exit; }; sleep 1; $io1->println('line 2'); $io1->println('line 3'); $io1->unlock; waitpid($pid, 0); } del_output_dir(); 1; glob.t100644001750001750 35712267312543 13176 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 1; use IO::All; use IO_All_Test; my @foo = sort map $_->filename, io()->dir(qw( t mydir ))->glob('f*'); is_deeply(\@foo, [qw( file1 file2 file3 )]); del_output_dir(); read.t100644001750001750 100112267312543 13171 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 8; use IO::All; use IO_All_Test; my $outfile = 't/out.pm'; ok(not -f $outfile); my $input = io('lib/IO/All.pm')->open; ok(ref $input); my $output = io($outfile)->open('>'); ok(ref $output); my $buffer; $input->buffer($buffer); $output->buffer($buffer); ok(defined $buffer); $output->write while $input->read; ok(not length($buffer)); ok($output->close); test_matching_files($outfile, 'lib/IO/All.pm'); ok($output->unlink); del_output_dir(); stat.t100644001750001750 122612267312543 13242 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 14; use IO::All; use IO_All_Test; my ($dev, $ino, $modes, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat('t/stat.t'); my $io = io('t/stat.t'); is($io->device, $dev); is($io->inode, $ino); is($io->modes, $modes); is($io->nlink, $nlink); is($io->uid, $uid); is($io->gid, $gid); is($io->device_id, $rdev); is($io->size, $size); ok(($io->atime == $atime) || ($io->atime == ($atime+1))); is($io->mtime, $mtime); is($io->ctime, $ctime); is($io->blksize, $blksize); is($io->blocks, $blocks); my @stat = $io->stat; ok(defined $stat[0]); del_output_dir(); META.yml100644001750001750 120112267312543 13101 0ustar00frewfrew000000000000IO-All-0.54--- abstract: 'IO::All of it to Graham and Damian!' author: - 'Ingy döt Net ' build_requires: {} configure_requires: ExtUtils::MakeMaker: 6.30 dynamic_config: 0 generated_by: 'Dist::Zilla version 5.006, CPAN::Meta::Converter version 2.132830' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: IO-All recommends: File::ReadBackwards: 0 requires: IO::String: 1.08 resources: bugtracker: https://github.com/ingydotnet/io-all-pm/issues homepage: https://github.com/ingydotnet/io-all-pm repository: https://github.com/ingydotnet/io-all-pm.git version: 0.54 MANIFEST100644001750001750 255612267312543 12777 0ustar00frewfrew000000000000IO-All-0.54Changes LICENSE MANIFEST META.json META.yml Makefile.PL Notes/Design.md Notes/Design.st README README.md ToDo cpanfile dist.ini examples/create-cat-to.pl lib/IO/All.pm lib/IO/All.pod lib/IO/All/Base.pm lib/IO/All/DBM.pm lib/IO/All/Dir.pm lib/IO/All/File.pm lib/IO/All/Filesys.pm lib/IO/All/Link.pm lib/IO/All/MLDBM.pm lib/IO/All/Pipe.pm lib/IO/All/STDIO.pm lib/IO/All/Socket.pm lib/IO/All/String.pm lib/IO/All/Temp.pm method_list pkg/manifest.skip t/IO_All_Test.pm t/IO_Dumper.pm t/RT81224.t t/absolute.t t/accept.t t/all.t t/all2.t t/append.t t/assert.t t/assert2.t t/autotie.t t/backwards.t t/chdir.t t/chomp.t t/construct.t t/dbm.t t/devnull.t t/empty.t t/encoding.t t/error1.t t/file_spec.t t/file_subclass.t t/fileno.t t/glob.t t/img.jpg t/import_flags.t t/in-place.t t/inline_subclass.t t/input.t t/link.t t/link2.t t/lock.t t/mldbm.t t/morestuff t/mydir/dir1/dira/dirx/file1 t/mydir/dir1/file1 t/mydir/dir2/file1 t/mydir/file1 t/mydir/file2 t/mydir/file3 t/mystuff t/new.t t/os.t t/overload.t t/pipe.t t/print.t t/println.t t/read.t t/read_write.t t/release-pod-syntax.t t/round_robin.t t/rt-41819.t t/scalar.t t/seek.t t/separator.t t/stat.t t/string_open.t t/subtleties.t t/synopsis1.t t/synopsis2.t t/synopsis3.t t/synopsis5.t t/text.big5 t/text.utf8 t/tie.t t/tie_file.t t/xxx.t unit/append.pl unit/client.pl unit/println.pl unit/server.pl unit/stdio.pl unit/test.pl unit/xxx.pl README.md100644001750001750 13407712267312543 13171 0ustar00frewfrew000000000000IO-All-0.54# NAME IO::All - IO::All of it to Graham and Damian! # SYNOPSIS use IO::All; # Let the madness begin... # Some of the many ways to read a whole file into a scalar io('file.txt') > $contents; # Overloaded "arrow" $contents < io 'file.txt'; # Flipped but same operation $io = io 'file.txt'; # Create a new IO::All object $contents = $$io; # Overloaded scalar dereference $contents = $io->all; # A method to read everything $contents = $io->slurp; # Another method for that $contents = join '', $io->getlines; # Join the separate lines $contents = join '', map "$_\n", @$io; # Same. Overloaded array deref $io->tie; # Tie the object as a handle $contents = join '', <$io>; # And use it in builtins # and the list goes on ... # Other file operations: @lines = io('file.txt')->slurp; # List context slurp $content > io('file.txt'); # Print to a file io('file.txt')->print($content, $more); # (ditto) $content >> io('file.txt'); # Append to a file io('file.txt')->append($content); # (ditto) $content << $io; # Append to a string io('copy.txt') < io('file.txt'); $ Copy a file io('file.txt') > io('copy.txt'); # Invokes File::Copy io('more.txt') >> io('all.txt'); # Add on to a file # UTF-8 Support $contents = io('file.txt')->utf8->all; # Turn on utf8 use IO::All -utf8; # Turn on utf8 for all io $contents = io('file.txt')->all; # by default in this package. # General Encoding Support $contents = io('file.txt')->encoding('big5')->all; use IO::All -encoding => 'big5'; # Turn on big5 for all io $contents = io('file.txt')->all; # by default in this package. # Print the path name of a file: print $io->name; # The direct method print "$io"; # Object stringifies to name print $io; # Quotes not needed here print $io->filename; # The file portion only $io->os('win32'); # change the object to be a # win32 path print $io->ext; # The file extension only print $io->mimetype; # The mimetype, requires # File::MimeType # Read all the files/directories in a directory: $io = io('my/directory/'); # Create new directory object @contents = $io->all; # Get all contents of dir @contents = @$io; # Directory as an array @contents = values %$io; # Directory as a hash push @contents, $subdir # One at a time while $subdir = $io->next; # Print the name and file type for all the contents above: print "$_ is a " . $_->type . "\n" # Each element of @contents for @contents; # is an IO::All object!! # Print first line of each file: print $_->getline # getline gets one line for io('dir')->all_files; # Files only # Print names of all files/dirs three directories deep: print "$_\n" for $io->all(3); # Pass in the depth. Default=1 # Print names of all files/dirs recursively: print "$_\n" for $io->all(0); # Zero means all the way down print "$_\n" for $io->All; # Capitalized shortcut print "$_\n" for $io->deep->all; # Another way # There are some special file names: print io('-'); # Print STDIN to STDOUT io('-') > io('-'); # Do it again io('-') < io('-'); # Same. Context sensitive. "Bad puppy" > io('='); # Message to STDERR $string_file = io('$'); # Create IO::String Object $temp_file = io('?'); # Create a temporary file # Socket operations: $server = io('localhost:5555')->fork; # Create a daemon socket $connection = $server->accept; # Get a connection socket $input < $connection; # Get some data from it "Thank you!" > $connection; # Thank the caller $connection->close; # Hang up io(':6666')->accept->slurp > io->devnull; # Take a complaint and file it # DBM database operations: $dbm = io 'my/database'; # Create a database object print $dbm->{grocery_list}; # Hash context makes it a DBM $dbm->{todo} = $new_list; # Write to database $dbm->dbm('GDBM_file'); # Demand specific DBM io('mydb')->mldbm->{env} = \%ENV; # MLDBM support # Tie::File support: $io = io 'file.txt'; $io->[42] = 'Line Forty Three'; # Change a line print $io->[@$io / 2]; # Print middle line @$io = reverse @$io; # Reverse lines in a file # Stat functions: printf "%s %s %s\n", # Print name, uid and size of $_->name, $_->uid, $_->size # contents of current directory for io('.')->all; print "$_\n" for sort # Use mtime method to sort all {$b->mtime <=> $a->mtime} # files under current directory io('.')->All_Files; # by recent modification time. # File::Spec support: $contents < io->catfile(qw(dir file.txt)); # Portable IO operation # Miscellaneous: @lines = io('file.txt')->chomp->slurp; # Chomp as you slurp @chunks = io('file.txt')->separator('xxx')->slurp; # Use alternnate record sep $binary = io('file.bin')->binary->all; # Read a binary file io('a-symlink')->readlink->slurp; # Readlink returns an object print io('foo')->absolute->pathname; # Print absolute path of foo # IO::All External Plugin Methods io("myfile") > io->("ftp://store.org"); # Upload a file using ftp $html < io->http("www.google.com"); # Grab a web page io('mailto:worst@enemy.net')->print($spam); # Email a "friend" # This is just the beginning, read on... # DESCRIPTION "Graham Barr for doing it all. Damian Conway for doing it all different." IO::All combines all of the best Perl IO modules into a single nifty object oriented interface to greatly simplify your everyday Perl IO idioms. It exports a single function called `io`, which returns a new IO::All object. And that object can do it all! The IO::All object is a proxy for IO::File, IO::Dir, IO::Socket, IO::String, Tie::File, File::Spec, File::Path, File::MimeInfo and File::ReadBackwards; as well as all the DBM and MLDBM modules. You can use most of the methods found in these classes and in IO::Handle (which they inherit from). IO::All adds dozens of other helpful idiomatic methods including file stat and manipulation functions. IO::All is pluggable, and modules like [IO::All::LWP](http://search.cpan.org/perldoc?IO::All::LWP) and [IO::All::Mailto](http://search.cpan.org/perldoc?IO::All::Mailto) add even more functionality. Optionally, every IO::All object can be tied to itself. This means that you can use most perl IO builtins on it: readline, <>, getc, print, printf, syswrite, sysread, close. The distinguishing magic of IO::All is that it will automatically open (and close) files, directories, sockets and other IO things for you. You never need to specify the mode ('<', '>>', etc), since it is determined by the usage context. That means you can replace this: open STUFF, '<', './mystuff' or die "Can't open './mystuff' for input:\n$!"; local $/; my $stuff = ; close STUFF; with this: my $stuff < io './mystuff'; And that is a __good thing__! # USAGE Normally just say: use IO::All; and IO::All will export a single function called `io`, which constructs all IO objects. You can also pass global flags like this: use IO::All -encoding => 'big5', -foobar; Which automatically makes those method calls on every new IO object. In other words this: my $io = io('lalala.txt'); becomes this: my $io = io('lalala.txt')->encoding('big5')->foobar; # METHOD ROLE CALL Here is an alphabetical list of all the public methods that you can call on an IO::All object. `abs2rel`, `absolute`, `accept`, `All`, `all`, `All_Dirs`, `all_dirs`, `All_Files`, `all_files`, `All_Links`, `all_links`, `append`, `appendf`, `appendln`, `assert`, `atime`, `autoclose`, `autoflush`, `backwards`, `bcc`, `binary`, `binmode`, `blksize`, `blocks`, `block_size`, `buffer`, `canonpath`, `case_tolerant`, `catdir`, `catfile`, `catpath`, `cc`, `chdir`, `chomp`, `clear`, `close`, `confess`, `content`, `ctime`, `curdir`, `dbm`, `deep`, `device`, `device_id`, `devnull`, `dir`, `domain`, `empty`, `ext`, `encoding`, `eof`, `errors`, `file`, `filename`, `fileno`, `filepath`, `filter`, `fork`, `from`, `ftp`, `get`, `getc`, `getline`, `getlines`, `gid`, `glob`, `handle`, `head`, `http`, `https`, `inode`, `io_handle`, `is_absolute`, `is_dir`, `is_dbm`, `is_executable`, `is_file`, `is_link`, `is_mldbm`, `is_open`, `is_pipe`, `is_readable`, `is_socket`, `is_stdio`, `is_string`, `is_temp`, `is_writable`, `join`, `length`, `link`, `lock`, `mailer`, `mailto`, `mimetype`, `mkdir`, `mkpath`, `mldbm`, `mode`, `modes`, `mtime`, `name`, `new`, `next`, `nlink`, `open`, `os` `password`, `path`, `pathname`, `perms`, `pipe`, `port`, `print`, `printf`, `println`, `put`, `rdonly`, `rdwr`, `read`, `readdir`, `readlink`, `recv`, `rel2abs`, `relative`, `rename`, `request`, `response`, `rmdir`, `rmtree`, `rootdir`, `scalar`, `seek`, `send`, `separator`, `shutdown`, `size`, `slurp`, `socket`, `sort`, `splitdir`, `splitpath`, `stat`, `stdio`, `stderr`, `stdin`, `stdout`, `string`, `string_ref`, `subject`, `sysread`, `syswrite`, `tail`, `tell`, `temp`, `tie`, `tmpdir`, `to`, `touch`, `truncate`, `type`, `user`, `uid`, `unlink`, `unlock`, `updir`, `uri`, `utf8`, `utime` and `write`. Each method is documented further below. # OPERATOR OVERLOADING IO::All objects overload a small set of Perl operators to great effect. The overloads are limited to <, <<, >, >>, dereferencing operations, and stringification. Even though relatively few operations are overloaded, there is actually a huge matrix of possibilities for magic. That's because the overloading is sensitive to the types, position and context of the arguments, and an IO::All object can be one of many types. The most important overload to become familiar with is stringification. IO::All objects stringify to their file or directory name. Here we print the contents of the current directory: perl -MIO::All -le 'print for io(".")->all' is the same as: perl -MIO::All -le 'print $_->name for io(".")->all' Stringification is important because it allows IO::All operations to return objects when they might otherwise return file names. Then the recipient can use the result either as an object or a string. '>' and '<' move data between objects in the direction pointed to by the operator. $content1 < io('file1'); $content1 > io('file2'); io('file2') > $content3; io('file3') < $content3; io('file3') > io('file4'); io('file5') < io('file4'); '>>' and '<<' do the same thing except the recipient string or file is appended to. An IO::All file used as an array reference becomes tied using Tie::File: $file = io "file"; # Print last line of file print $file->[-1]; # Insert new line in middle of file $file->[$#$file / 2] = 'New line'; An IO::All file used as a hash reference becomes tied to a DBM class: io('mydbm')->{ingy} = 'YAML'; An IO::All directory used as an array reference, will expose each file or subdirectory as an element of the array. print "$_\n" for @{io 'dir'}; IO::All directories used as hash references have file names as keys, and IO::All objects as values: print io('dir')->{'foo.txt'}->slurp; Files used as scalar references get slurped: print ${io('dir')->{'foo.txt'}}; Not all combinations of operations and object types are supported. Some just haven't been added yet, and some just don't make sense. If you use an invalid combination, an error will be thrown. # COOKBOOK This section describes some various things that you can easily cook up with IO::All. ## File Locking IO::All makes it very easy to lock files. Just use the `lock` method. Here's a standalone program that demonstrates locking for both write and read: use IO::All; my $io1 = io('myfile')->lock; $io1->println('line 1'); fork or do { my $io2 = io('myfile')->lock; print $io2->slurp; exit; }; sleep 1; $io1->println('line 2'); $io1->println('line 3'); $io1->unlock; There are a lot of subtle things going on here. An exclusive lock is issued for `$io1` on the first `println`. That's because the file isn't actually opened until the first IO operation. When the child process tries to read the file using `$io2`, there is a shared lock put on it. Since `$io1` has the exclusive lock, the slurp blocks. The parent process sleeps just to make sure the child process gets a chance. The parent needs to call `unlock` or `close` to release the lock. If all goes well the child will print 3 lines. ## Round Robin This simple example will read lines from a file forever. When the last line is read, it will reopen the file and read the first one again. my $io = io 'file1.txt'; $io->autoclose(1); while (my $line = $io->getline || $io->getline) { print $line; } ## Reading Backwards If you call the `backwards` method on an IO::All object, the `getline` and `getlines` will work in reverse. They will read the lines in the file from the end to the beginning. my @reversed; my $io = io('file1.txt'); $io->backwards; while (my $line = $io->getline) { push @reversed, $line; } or more simply: my @reversed = io('file1.txt')->backwards->getlines; The `backwards` method returns the IO::All object so that you can chain the calls. NOTE: This operation requires that you have the [File::ReadBackwards](http://search.cpan.org/perldoc?File::ReadBackwards) module installed. ## Client/Server Sockets IO::All makes it really easy to write a forking socket server and a client to talk to it. In this example, a server will return 3 lines of text, to every client that calls it. Here is the server code: use IO::All; my $socket = io(':12345')->fork->accept; $socket->print($_) while ; $socket->close; __DATA__ On your mark, Get set, Go! Here is the client code: use IO::All; my $io = io('localhost:12345'); print while $_ = $io->getline; You can run the server once, and then run the client repeatedly (in another terminal window). It should print the 3 data lines each time. Note that it is important to close the socket if the server is forking, or else the socket won't go out of scope and close. ## A Tiny Web Server Here is how you could write a simplistic web server that works with static and dynamic pages: perl -MIO::All -e 'io(":8080")->fork->accept->(sub { $_[0] < io(-x $1 ? "./$1 |" : $1) if /^GET \/(.*) / })' There is are a lot of subtle things going on here. First we accept a socket and fork the server. Then we overload the new socket as a code ref. This code ref takes one argument, another code ref, which is used as a callback. The callback is called once for every line read on the socket. The line is put into `$_` and the socket itself is passed in to the callback. Our callback is scanning the line in `$_` for an HTTP GET request. If one is found it parses the file name into `$1`. Then we use `$1` to create an new IO::All file object... with a twist. If the file is executable (`-x`), then we create a piped command as our IO::All object. This somewhat approximates CGI support. Whatever the resulting object is, we direct the contents back at our socket which is in `$_[0]`. Pretty simple, eh? ## DBM Files IO::All file objects used as a hash reference, treat the file as a DBM tied to a hash. Here I write my DB record to STDERR: io("names.db")->{ingy} > io('='); Since their are several DBM formats available in Perl, IO::All picks the first one of these that is installed on your system: DB_File GDBM_File NDBM_File ODBM_File SDBM_File You can override which DBM you want for each IO::All object: my @keys = keys %{io('mydbm')->dbm('SDBM_File')}; ## File Subclassing Subclassing is easy with IO::All. Just create a new module and use IO::All as the base class, like this: package NewModule; use IO::All -base; You need to do it this way so that IO::All will export the `io` function. Here is a simple recipe for subclassing: IO::Dumper inherits everything from IO::All and adds an extra method called `dump`, which will dump a data structure to the file we specify in the `io` function. Since it needs Data::Dumper to do the dumping, we override the `open` method to `require Data::Dumper` and then pass control to the real `open`. First the code using the module: use IO::Dumper; io('./mydump')->dump($hash); And next the IO::Dumper module itself: package IO::Dumper; use IO::All -base; use Data::Dumper; sub dump { my $self = shift; Dumper(@_) > $self; } 1; ## Inline Subclassing This recipe does the same thing as the previous one, but without needing to write a separate module. The only real difference is the first line. Since you don't "use" IO::Dumper, you need to still call its `import` method manually. IO::Dumper->import; io('./mydump')->dump($hash); package IO::Dumper; use IO::All -base; use Data::Dumper; sub dump { my $self = shift; Dumper(@_) > $self; } # THE IO::All METHODS This section gives a full description of all of the methods that you can call on IO::All objects. The methods have been grouped into subsections based on object construction, option settings, configuration, action methods and support for specific modules. ## Object Construction and Initialization Methods - new There are three ways to create a new IO::All object. The first is with the special function `io` which really just calls `IO::All->new`. The second is by calling `new` as a class method. The third is calling `new` as an object instance method. In this final case, the new objects attributes are copied from the instance object. io(file-descriptor); IO::All->new(file-descriptor); $io->new(file-descriptor); All three forms take a single argument, a file descriptor. A file descriptor can be any of the following: - A file name - A file handle - A directory name - A directory handle - A typeglob reference - A piped shell command. eq '| ls -al' - A socket domain/port. eg 'perl.com:5678' - '-' means STDIN or STDOUT (depending on usage) - '=' means STDERR - '$' means an IO::String object - '?' means a temporary file - A URI including: http, https, ftp and mailto - An IO::All object If you provide an IO::All object, you will simply get that _same object_ returned from the constructor. If no file descriptor is provided, an object will still be created, but it must be defined by one of the following methods before it can be used for I/O: - file io->file("path/to/my/file.txt"); Using the `file` method sets the type of the object to _file_ and sets the pathname of the file if provided. It might be important to use this method if you had a file whose name was `'-'`, or if the name might otherwise be confused with a directory or a socket. In this case, either of these statements would work the same: my $file = io('-')->file; my $file = io->file('-'); - dir io->file($dir_name); Make the object be of type _directory_. - socket io->socket("${domain}:${port}"); Make the object be of type _socket_. - link io->link($link_name); Make the object be of type _link_. - pipe io->pipe($pipe_command); Make the object be of type _pipe_. The following two statements are equivalent: my $io = io('ls -l |'); my $io = io('ls -l')->pipe; my $io = io->pipe('ls -l'); - dbm This method takes the names of zero or more DBM modules. The first one that is available is used to process the dbm file. io('mydbm')->dbm('NDBM_File', 'SDBM_File')->{author} = 'ingy'; If no module names are provided, the first available of the following is used: DB_File GDBM_File NDBM_File ODBM_File SDBM_File - mldbm Similar to the `dbm` method, except create a Multi Level DBM object using the MLDBM module. This method takes the names of zero or more DBM modules and an optional serialization module. The first DBM module that is available is used to process the MLDBM file. The serialization module can be Data::Dumper, Storable or FreezeThaw. io('mymldbm')->mldbm('GDBM_File', 'Storable')->{author} = {nickname => 'ingy'}; - string Make the object be an IO::String object. These are equivalent: my $io = io('$'); my $io = io->string; - temp Make the object represent a temporary file. It will automatically be open for both read and write. - stdio Make the object represent either STDIN or STDOUT depending on how it is used subsequently. These are equivalent: my $io = io('-'); my $io = io->stdin; - stdin Make the object represent STDIN. - stdout Make the object represent STDOUT. - stderr Make the object represent STDERR. - handle io->handle($io_handle); Forces the object to be created from an pre-existing IO handle. You can chain calls together to indicate the type of handle: my $file_object = io->file->handle($file_handle); my $dir_object = io->dir->handle($dir_handle); - http Make the object represent an HTTP URI. Requires IO-All-LWP. - https Make the object represent an HTTPS URI. Requires IO-All-LWP. - ftp Make the object represent an FTP URI. Requires IO-All-LWP. - mailto Make the object represent a `mailto:` URI. Requires IO-All-Mailto. If you need to use the same options to create a lot of objects, and don't want to duplicate the code, just create a dummy object with the options you want, and use that object to spawn other objects. my $lt = io->lock->tie; ... my $io1 = $lt->new('file1'); my $io2 = $lt->new('file2'); Since the new method copies attributes from the calling object, both `$io1` and `$io2` will be locked and tied. ## Option Setting Methods The following methods don't do any actual I/O, but they specify options about how the I/O should be done. Each option can take a single argument of 0 or 1. If no argument is given, the value 1 is assumed. Passing 0 turns the option off. All of these options return the object reference that was used to invoke them. This is so that the option methods can be chained together. For example: my $io = io('path/file')->tie->assert->chomp->lock; - absolute Indicates that the `pathname` for the object should be made absolute. # Print the full path of the current working directory # (like pwd). use IO::All; print io->curdir->absolute; - assert This method ensures that the path for a file or directory actually exists before the file is open. If the path does not exist, it is created. For example, here is a program called "create-cat-to" that outputs to a file that it creates. #!/usr/bin/perl # create-cat-to.pl # cat to a file that can be created. use strict; use warnings; use IO::All; my $filename = shift(@ARGV); # Create a file called $filename, including all leading components. io('-') > io->file($filename)->assert; Here's an example use of it: $ ls -l total 0 $ echo "Hello World" | create-cat-to one/two/three/four.txt $ ls -l total 4 drwxr-xr-x 3 shlomif shlomif 4096 2010-10-14 18:03 one/ $ cat one/two/three/four.txt Hello World $ - autoclose By default, IO::All will close an object opened for input when EOF is reached. By closing the handle early, one can immediately do other operations on the object without first having to close it. This option is on by default, so if you don't want this behaviour, say so like this: $io->autoclose(0); The object will then be closed when `$io` goes out of scope, or you manually call `$io->close`. - autoflush Proxy for IO::Handle::autoflush - backwards Sets the object to 'backwards' mode. All subsequent `getline` operations will read backwards from the end of the file. Requires the File::ReadBackwards CPAN module. - binary Indicates the file has binary content and should be opened with `binmode`. - chdir chdir() to the pathname of a directory object. When object goes out of scope, chdir back to starting directory. - chomp Indicates that all operations that read lines should chomp the lines. If the `separator` method has been called, chomp will remove that value from the end of each record. - confess Errors should be reported with the very detailed Carp::confess function. - deep Indicates that calls to the `all` family of methods should search directories as deep as possible. - fork Indicates that the process should automatically be forked inside the `accept` socket method. - lock Indicate that operations on an object should be locked using flock. - rdonly This option indicates that certain operations like DBM and Tie::File access should be done in read-only mode. - rdwr This option indicates that DBM and MLDBM files should be opened in read- write mode. - relative Indicates that the `pathname` for the object should be made relative. - sort Indicates whether objects returned from one of the `all` methods will be in sorted order by name. True by default. - tie Indicate that the object should be tied to itself, thus allowing it to be used as a filehandle in any of Perl's builtin IO operations. my $io = io('foo')->tie; @lines = <$io>; - utf8 Indicates that IO should be done using utf8 encoding. Calls binmode with `:utf8` layer. ## Configuration Methods The following methods don't do any actual I/O, but they set specific values to configure the IO::All object. If these methods are passed no argument, they will return their current value. If arguments are passed they will be used to set the current value, and the object reference will be returned for potential method chaining. - bcc Set the Bcc field for a mailto object. - binmode Proxy for binmode. Requires a layer to be passed. Use `binary` for plain binary mode. - block\_size The default length to be used for `read` and `sysread` calls. Defaults to 1024. - buffer Returns a reference to the internal buffer, which is a scalar. You can use this method to set the buffer to a scalar of your choice. (You can just pass in the scalar, rather than a reference to it.) This is the buffer that `read` and `write` will use by default. You can easily have IO::All objects use the same buffer: my $input = io('abc'); my $output = io('xyz'); my $buffer; $output->buffer($input->buffer($buffer)); $output->write while $input->read; - cc Set the Cc field for a mailto object. - content Get or set the content for an LWP operation manually. - domain Set the domain name or ip address that a socket should use. - encoding Set the encoding to be used for the PerlIO layer. - errors Use this to set a subroutine reference that gets called when an internal error is thrown. - filter Use this to set a subroutine reference that will be used to grep which objects get returned on a call to one of the `all` methods. For example: my @odd = io->curdir->filter(sub {$_->size % 2})->All_Files; `@odd` will contain all the files under the current directory whose size is an odd number of bytes. - from Indicate the sender for a mailto object. - mailer Set the mailer program for a mailto transaction. Defaults to 'sendmail'. - mode Set the mode for which the file should be opened. Examples: $io->mode('>>')->open; $io->mode(O_RDONLY); my $log_appender = io->file('/var/log/my-application.log') ->mode('>>')->open(); $log_appender->print("Stardate 5987.6: Mission accomplished."); - name Set or get the name of the file or directory represented by the IO::All object. - password Set the password for an LWP transaction. - perms Sets the permissions to be used if the file/directory needs to be created. - port Set the port number that a socket should use. - request Manually specify the request object for an LWP transaction. - response Returns the resulting response object from an LWP transaction. - separator Sets the record (line) separator to whatever value you pass it. Default is \\n. Affects the chomp setting too. - string\_ref Proxy for IO::String::string\_ref Returns a reference to the internal string that is acting like a file. - subject Set the subject for a mailto transaction. - to Set the recipient address for a mailto request. - uri Direct access to the URI used in LWP transactions. - user Set the user name for an LWP transaction. ## IO Action Methods These are the methods that actually perform I/O operations on an IO::All object. The stat methods and the File::Spec methods are documented in separate sections below. - accept For sockets. Opens a server socket (LISTEN => 1, REUSE => 1). Returns an IO::All socket object that you are listening on. If the `fork` method was called on the object, the process will automatically be forked for every connection. - all Read all contents into a single string. compare(io('file1')->all, io('file2')->all); - all (For directories) Returns a list of IO::All objects for all files and subdirectories in a directory. '.' and '..' are excluded. Takes an optional argument telling how many directories deep to search. The default is 1. Zero (0) means search as deep as possible. The filter method can be used to limit the results. The items returned are sorted by name unless `->sort(0)` is used. - All Same as `all(0)`. - all\_dirs Same as `all`, but only return directories. - All\_Dirs Same as `all_dirs(0)`. - all\_files Same as `all`, but only return files. - All\_Files Same as `all_files(0)`. - all\_links Same as `all`, but only return links. - All\_Links Same as `all_links(0)`. - append Same as print, but sets the file mode to '>>'. - appendf Same as printf, but sets the file mode to '>>'. - appendln Same as println, but sets the file mode to '>>'. - clear Clear the internal buffer. This method is called by `write` after it writes the buffer. Returns the object reference for chaining. - close Close will basically unopen the object, which has different meanings for different objects. For files and directories it will close and release the handle. For sockets it calls shutdown. For tied things it unties them, and it unlocks locked things. - empty Returns true if a file exists but has no size, or if a directory exists but has no contents. - eof Proxy for IO::Handle::eof - ext Returns the extension of the file. Can also be spelled as `extension` - exists Returns whether or not the file or directory exists. - filename Return the name portion of the file path in the object. For example: io('my/path/file.txt')->filename; would return `file.txt`. - fileno Proxy for IO::Handle::fileno - filepath Return the path portion of the file path in the object. For example: io('my/path/file.txt')->filename; would return `my/path`. - get Perform an LWP GET request manually. - getc Proxy for IO::Handle::getc - getline Calls IO::File::getline. You can pass in an optional record separator. - getlines Calls IO::File::getlines. You can pass in an optional record separator. - glob Creates IO::All objects for the files matching the glob in the IO::All::Dir. For example: io->dir($ENV{HOME})->glob('*.txt') - head Return the first 10 lines of a file. Takes an optional argument which is the number of lines to return. Works as expected in list and scalar context. Is subject to the current line separator. - io\_handle Direct access to the actual IO::Handle object being used on an opened IO::All object. - is\_dir Returns boolean telling whether or not the IO::All object represents a directory. - is\_executable Returns true if file or directory is executable. - is\_dbm Returns boolean telling whether or not the IO::All object represents a dbm file. - is\_file Returns boolean telling whether or not the IO::All object represents a file. - is\_link Returns boolean telling whether or not the IO::All object represents a symlink. - is\_mldbm Returns boolean telling whether or not the IO::All object represents a mldbm file. - is\_open Indicates whether the IO::All is currently open for input/output. - is\_pipe Returns boolean telling whether or not the IO::All object represents a pipe operation. - is\_readable Returns true if file or directory is readable. - is\_socket Returns boolean telling whether or not the IO::All object represents a socket. - is\_stdio Returns boolean telling whether or not the IO::All object represents a STDIO file handle. - is\_string Returns boolean telling whether or not the IO::All object represents an IO::String object. - is\_temp Returns boolean telling whether or not the IO::All object represents a temporary file. - is\_writable Returns true if file or directory is writable. Can also be spelled as `is_writeable`. - length Return the length of the internal buffer. - mimetype Return the mimetype of the file. Requires the [File::MimeInfo](http://search.cpan.org/perldoc?File::MimeInfo) CPAN module. - mkdir Create the directory represented by the object. - mkpath Create the directory represented by the object, when the path contains more than one directory that doesn't exist. Proxy for File::Path::mkpath. - next For a directory, this will return a new IO::All object for each file or subdirectory in the directory. Return undef on EOD. - open Open the IO::All object. Takes two optional arguments `mode` and `perms`, which can also be set ahead of time using the `mode` and `perms` methods. NOTE: Normally you won't need to call open (or mode/perms), since this happens automatically for most operations. - os Change the object's os representation. Valid options are: `win32`, `unix`, `vms`, `mac`, `os2`. - pathname Return the absolute or relative pathname for a file or directory, depending on whether object is in `absolute` or `relative` mode. - print Proxy for IO::Handle::print - printf Proxy for IO::Handle::printf - println Same as print, but adds newline to each argument unless it already ends with one. - put Perform an LWP PUT request manually. - read This method varies depending on its context. Read carefully (no pun intended). For a file, this will proxy IO::File::read. This means you must pass it a buffer, a length to read, and optionally a buffer offset for where to put the data that is read. The function returns the length actually read (which is zero at EOF). If you don't pass any arguments for a file, IO::All will use its own internal buffer, a default length, and the offset will always point at the end of the buffer. The buffer can be accessed with the `buffer` method. The length can be set with the `block_size` method. The default length is 1024 bytes. The `clear` method can be called to clear the buffer. For a directory, this will proxy IO::Dir::read. - readdir Similar to the Perl `readdir` builtin. In scalar context, return the next directory entry (ie file or directory name), or undef on end of directory. In list context, return all directory entries. Note that `readdir` does not return the special `.` and `..` entries. - readline Same as `getline`. - readlink Calls Perl's readlink function on the link represented by the object. Instead of returning the file path, it returns a new IO::All object using the file path. - recv Proxy for IO::Socket::recv - rename my $new = $io->rename('new-name'); Calls Perl's rename function and returns an IO::All object for the renamed file. Returns false if the rename failed. - rewind Proxy for IO::Dir::rewind - rmdir Delete the directory represented by the IO::All object. - rmtree Delete the directory represented by the IO::All object and all the files and directories beneath it. Proxy for File::Path::rmtree. - scalar Deprecated. Same as `all()`. - seek Proxy for IO::Handle::seek. If you use seek on an unopened file, it will be opened for both read and write. - send Proxy for IO::Socket::send - shutdown Proxy for IO::Socket::shutdown - slurp Read all file content in one operation. Returns the file content as a string. In list context returns every line in the file. - stat Proxy for IO::Handle::stat - sysread Proxy for IO::Handle::sysread - syswrite Proxy for IO::Handle::syswrite - tail Return the last 10 lines of a file. Takes an optional argument which is the number of lines to return. Works as expected in list and scalar context. Is subject to the current line separator. - tell Proxy for IO::Handle::tell - throw This is an internal method that gets called whenever there is an error. It could be useful to override it in a subclass, to provide more control in error handling. - touch Update the atime and mtime values for a file or directory. Creates an empty file if the file does not exist. - truncate Proxy for IO::Handle::truncate - type Returns a string indicated the type of io object. Possible values are: file dir link socket string pipe Returns undef if type is not determinable. - unlink Unlink (delete) the file represented by the IO::All object. NOTE: You can unlink a file after it is open, and continue using it until it is closed. - unlock Release a lock from an object that used the `lock` method. - utime Proxy for the utime Perl function. - write Opposite of `read` for file operations only. NOTE: When used with the automatic internal buffer, `write` will clear the buffer after writing it. ## Stat Methods This methods get individual values from a stat call on the file, directory or handle represented by the IO::All object. - atime Last access time in seconds since the epoch - blksize Preferred block size for file system I/O - blocks Actual number of blocks allocated - ctime Inode change time in seconds since the epoch - device Device number of filesystem - device\_id Device identifier for special files only - gid Numeric group id of file's owner - inode Inode number - modes File mode - type and permissions - mtime Last modify time in seconds since the epoch - nlink Number of hard links to the file - size Total size of file in bytes - uid Numeric user id of file's owner ## File::Spec Methods These methods are all adaptations from File::Spec. Each method actually does call the matching File::Spec method, but the arguments and return values differ slightly. Instead of being file and directory __names__, they are IO::All __objects__. Since IO::All objects stringify to their names, you can generally use the methods just like File::Spec. - abs2rel Returns the relative path for the absolute path in the IO::All object. Can take an optional argument indicating the base path. - canonpath Returns the canonical path for the IO::All object. - case\_tolerant Returns 0 or 1 indicating whether the file system is case tolerant. Since an active IO::All object is not needed for this function, you can code it like: IO::All->case_tolerant; or more simply: io->case_tolerant; - catdir Concatenate the directory components together, and return a new IO::All object representing the resulting directory. - catfile Concatenate the directory and file components together, and return a new IO::All object representing the resulting file. my $contents = io->catfile(qw(dir subdir file))->slurp; This is a very portable way to read `dir/subdir/file`. - catpath Concatenate the volume, directory and file components together, and return a new IO::All object representing the resulting file. - curdir Returns an IO::All object representing the current directory. - devnull Returns an IO::All object representing the /dev/null file. - is\_absolute Returns 0 or 1 indicating whether the `name` field of the IO::All object is an absolute path. - join Same as `catfile`. - path Returns a list of IO::All directory objects for each directory in your path. - rel2abs Returns the absolute path for the relative path in the IO::All object. Can take an optional argument indicating the base path. - rootdir Returns an IO::All object representing the root directory on your file system. - splitdir Returns a list of the directory components of a path in an IO::All object. - splitpath Returns a volume directory and file component of a path in an IO::All object. - tmpdir Returns an IO::All object representing a temporary directory on your file system. - updir Returns an IO::All object representing the current parent directory. # OPERATIONAL NOTES - Each IO::All object gets reblessed into an IO::All::\* object as soon as IO::All can determine what type of object it should be. Sometimes it gets reblessed more than once: my $io = io('mydbm.db'); $io->dbm('DB_File'); $io->{foo} = 'bar'; In the first statement, $io has a reference value of 'IO::All::File', if `mydbm.db` exists. In the second statement, the object is reblessed into class 'IO::All::DBM'. - An IO::All object will automatically be opened as soon as there is enough contextual information to know what type of object it is, and what mode it should be opened for. This is usually when the first read or write operation is invoked but might be sooner. - The mode for an object to be opened with is determined heuristically unless specified explicitly. - For input, IO::All objects will automatically be closed after EOF (or EOD). For output, the object closes when it goes out of scope. To keep input objects from closing at EOF, do this: $io->autoclose(0); - You can always call `open` and `close` explicitly, if you need that level of control. To test if an object is currently open, use the `is_open` method. - Overloaded operations return the target object, if one exists. This would set `$xxx` to the IO::All object: my $xxx = $contents > io('file.txt'); While this would set `$xxx` to the content string: my $xxx = $contents < io('file.txt'); # STABILITY The goal of the IO::All project is to continually refine the module to be as simple and consistent to use as possible. Therefore, in the early stages of the project, I will not hesitate to break backwards compatibility with other versions of IO::All if I can find an easier and clearer way to do a particular thing. IO is tricky stuff. There is definitely more work to be done. On the other hand, this module relies heavily on very stable existing IO modules; so it may work fairly well. I am sure you will find many unexpected "features". Please send all problems, ideas and suggestions to ingy@cpan.org. ## Known Bugs and Deficiencies Not all possible combinations of objects and methods have been tested. There are many many combinations. All of the examples have been tested. If you find a bug with a particular combination of calls, let me know. If you call a method that does not make sense for a particular object, the result probably won't make sense. Little attempt is made to check for improper usage. # SEE ALSO IO::Handle, IO::File, IO::Dir, IO::Socket, IO::String, File::Spec, File::Path, File::ReadBackwards, Tie::File, File::MimeInfo # CREDITS A lot of people have sent in suggestions, that have become a part of IO::All. Thank you. Special thanks to Ian Langworth for continued testing and patching. Thank you Simon Cozens for tipping me off to the overloading possibilities. Finally, thanks to Autrijus Tang, for always having one more good idea. (It seems IO::All of it to a lot of people!) # REPOSITORY AND COMMUNITY The IO::All module can be found on CPAN and on GitHub: [http://github.com/ingydotnet/io-all-pm](http://github.com/ingydotnet/io-all-pm). Please join the IO::All discussion on \#io-all on irc.perl.org. # AUTHOR Ingy döt Net # COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008, 2010. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See [http://www.perl.com/perl/misc/Artistic.html](http://www.perl.com/perl/misc/Artistic.html) input.t100644001750001750 217612267312543 13433 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 12; use IO::All; use IO_All_Test; io('t/input.t') > my $contents; test_file_contents($contents, 't/input.t'); $contents < io 't/input.t'; test_file_contents($contents, 't/input.t'); my $io = io 't/input.t'; $contents = $$io; test_file_contents($contents, 't/input.t'); $contents = $io->slurp; test_file_contents($contents, 't/input.t'); $contents = $io->scalar; test_file_contents($contents, 't/input.t'); $contents = join '', $io->getlines; test_file_contents($contents, 't/input.t'); SKIP: { eval {require Tie::File}; skip "requires Tie::File", 2 if $@; $io->rdonly; $contents = join '', map "$_\n", @$io; test_file_contents($contents, 't/input.t'); $io->close; $io->tie; $contents = join '', <$io>; test_file_contents($contents, 't/input.t'); } my @lines = io('t/input.t')->slurp; ok(@lines > 36); test_file_contents(join('', @lines), 't/input.t'); my $old_contents = $contents; $contents << io('t/input.t'); is($contents, $old_contents . $old_contents); is(io('t/input.t') >> $contents, ($old_contents x 3)); del_output_dir(); chdir.t100644001750001750 34712267312543 13343 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 1; use IO::All; use IO_All_Test; use Cwd; { my $dir = io('t')->chdir; is((io(io->curdir->absolute->pathname)->splitdir)[-1], 't'); } del_output_dir(); print.t100644001750001750 52212267312543 13401 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 2; use IO::All; use IO_All_Test; my $io1 = io(o_dir() . '/print.t'); is($io1->print("one\n")->print("two\n")->close->scalar, "one\ntwo\n"); my $io2 = io(o_dir() . '/print.t'); is($io2->println("one")->println("two")->close->scalar, "one\ntwo\n"); del_output_dir(); link2.t100644001750001750 75712267312543 13276 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More; use IO::All; use IO_All_Test; use Cwd qw(abs_path); my $linkname = o_dir() . '/mylink'; my $cwd = abs_path('.'); eval { symlink("t/mydir", $linkname) or die $! }; if ($@ or not -l $linkname) { plan skip_all => 'Cannot call symlink on this platform'; } else { plan tests => 2; } my $io = io($linkname); my @files = $io->all_files; is(scalar @files, 3); @files = $io->All_Files; is(scalar @files, 6); del_output_dir(); empty.t100644001750001750 47412267312543 13411 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 5; use IO::All; use IO_All_Test; my $d = io(o_dir() . '/empty'); ok($d->mkdir); ok($d->empty); my $f = io(o_dir() . '/file'); ok($f->touch->touch); ok($f->empty); eval {io('qwerty')->empty}; like($@, qr"Can't call empty"); del_output_dir(); img.jpg100644001750001750 1205012267312543 13375 0ustar00frewfrew000000000000IO-All-0.54/tPNG  IHDRMm PLTE """&&&***...222666:::>>>BBBFFFJJJNNNRRRVVVZZZ^^^bbbfffjjjnnnrrrvvvzzz~~~JtRNS@f pHYs  IDATx\v"ERd UJ03oh-]iW\v*xRb%R z.*qXA(vB\qGmBYX7q #@}$) (:cD(MrV=vq 6ŮH 1s!Z`qxu8OնJi %[ߧpX`e"P2?ib凛,\Ja{cգ\SSeW Wd˭8Fl3(  0 U􈝑j, (DN~Qĝ3E J⹖&+(xç tMS\=il ^)7WPc;#A97᫊b;ߥi@g?qλ%[Mfe֏p?fR[݅PcL9ԀHzYB(i#mmj=n*@STMm\d'r|B$´r&=S2Q%wK.6rZQbK~}nOCBv;#wn4EH`#*[hQʄ) ɘ:HRЋGAk97p"Agf)  53'唰<L(էud"kPG r@JR;~.=XJͻ -(fpgN_&2D S(du PQ3N;ЇeЀ11ڱ5%bL %6Ṡm_BJVF e/ZiOa:ޜ-~ekrˏSgxg=3pn"ڍL@d *'rI$(S W @ f<LjES;5"{!t'#! _)(㧍؀@0A̷m3m߻+{0́T@0#? I@40sa1Kw70h B t q5\F.:L!H;jq[Drn1{,VA :G½}uׇ_`(qCE%|,m ގ$$bsusľ+r#iW&0HLCQ(ljW4 25j, 1H6OFܦ*RwOVb0+bgN~a:VT%}Dxb,AS@R؆h bQ81jul`yQ+l yJsuB&OhX&]@D)Ttzqf3?)*++m`(W ":QZ4B狦Wg.G ޿P]^A%hqMmT1,RNX2uu qqݥռ JJ MQ]ǨN(OWf4L:c.d:d]"nմK)>-I}7kצ2^EJ&QıtSϿ.x#~ O4hzkdEw@$&xZ:Ѥ$Y-F *$v@ <9܈5AjDdsr*b)ݽ5i2(kgD&D} ))tv5z!I<&l5^ؘ|IfӶ'~U>i0]׺h Lf.&i#_JxPh= Re@8Q,˶bR/Vod>[k0*iB ?)Zu[#F16-mu J&aT-7>zuݸ Mi nAbXlSUzW_딙iJct~Ă&NO;)tj V(||RqihaYqi__L0Lxca HKb8ϝZDHS_[1I&=ne`U.?C!ZuH2 qPmܮ:`#|zF#VKEB=Ja+YMp%傌K2Xr^zAEHhFTǽe? \ UG{0[xWYȍl [P*MU8ZΫte<~N0 fnR+r1|%/xH Y$ASkqo|nwNq*SS77ӧM74L:r:WO!(˲$0E>=aK8X\' _8zkjf/Yjz.:,o`e%@G!\m>B@ n_9Dz%_&99w4|GRiy.!^c0W٠Yu\ #2zϙq#chomp; for ($io->slurp) { ok(not /\n/); } $io->close; for ($io->chomp->separator('io')->getlines) { ok(not /io/); } del_output_dir(); mldbm.t100644001750001750 107012267312543 13357 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More; use IO::All; use IO_All_Test; plan((eval {require MLDBM; 1}) ? (tests => 4) : (skip_all => "requires MLDBM") ); my $io = io(o_dir() . '/mldbm')->mldbm('SDBM_File', 'Data::Dumper'); $io->{test} = { qw( foo foolsgold bar bargain baz bazzarro ) }; $io->{test2} = [ 1..4 ]; $io->close; my $io2 = io(o_dir() . '/mldbm')->mldbm('SDBM_File', 'Data::Dumper'); is(scalar(@{[%$io2]}), 4); is(scalar(@{[%{$io2->{test}}]}), 6); is($io2->{test}{bar}, 'bargain'); is($io2->{test2}[3], 4); del_output_dir(); META.json100644001750001750 232012267312543 13254 0ustar00frewfrew000000000000IO-All-0.54{ "abstract" : "IO::All of it to Graham and Damian!", "author" : [ "Ingy d\u00f6t Net " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.006, CPAN::Meta::Converter version 2.132830", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "IO-All", "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.30" } }, "develop" : { "requires" : { "Test::Pod" : "1.41" } }, "runtime" : { "recommends" : { "File::ReadBackwards" : "0" }, "requires" : { "IO::String" : "1.08" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/ingydotnet/io-all-pm/issues" }, "homepage" : "https://github.com/ingydotnet/io-all-pm", "repository" : { "type" : "git", "url" : "https://github.com/ingydotnet/io-all-pm.git", "web" : "https://github.com/ingydotnet/io-all-pm" } }, "version" : "0.54" } error1.t100644001750001750 43412267312543 13461 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 2; use IO::All; my $t1 = io('quack'); eval { $t1->slurp; }; like($@, qr{^Can't open file 'quack' for input:}); my $t2 = io('t/xxxxx'); eval { $t2->next; }; like($@, qr{^Can't open directory 't/xxxxx':}); accept.t100644001750001750 323512267312543 13530 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 20; use IO::All; use IO_All_Test; use IO::Socket::INET; # This test tests for the ability of a non-forking socket to handle more # than one connection. my $pid = fork(); if (! $pid) { # Let the child process listen on a port my $port = 5555; my $accepted = 0; while (1) { # Log the port to a file. open my $out, ">", o_dir() . "/server-port.t"; print {$out} $port; close($out); my $server = io("localhost:$port"); eval { for my $count (1 .. 10) { my $connection = $server->accept(); $accepted = 1; $connection->print(sprintf("Ingy-%.2d", $count)); $connection->close(); } }; if ($accepted) { # We have a listening socket on a port, so we can continue last; } } continue { # Try a different port. $port++; } exit(0); } # Let the parent process handle the testing. # Wait a little for the client to find a port. sleep(1); open my $in, "<", o_dir() . "/server-port.t"; my $port = <$in>; close($in); # TEST*2*10 for my $c (1 .. 10) { my $sock = IO::Socket::INET->new( PeerAddr => "localhost", PeerPort => $port, Proto => "tcp" ); ok(defined($sock), "Checking for validity of sock No. $c"); if (!defined($sock)) { last; } my $data; $sock->recv($data, 7); $sock->close(); is ($data, sprintf("Ingy-%.2d", $c), "Checking for connection No. $c."); } waitpid($pid, 0); del_output_dir(); fileno.t100644001750001750 106612267312543 13545 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More; use IO::All; use IO_All_Test; plan((lc($^O) eq 'mswin32' and defined $ENV{PERL5_CPANPLUS_IS_RUNNING}) ? (skip_all => "CPANPLUS/MSWin32 breaks this") : ($] < 5.008003) ? (skip_all => 'Broken on older perls') : (tests => 7) ); is(io('-')->mode('<')->open->fileno, 0); is(io('-')->mode('>')->open->fileno, 1); is(io('=')->fileno, 2); is(io->stdin->fileno, 0); is(io->stdout->fileno, 1); is(io->stderr->fileno, 2); ok(io(o_dir() . '/xxx')->open('>')->fileno > 2); del_output_dir(); scalar.t100644001750001750 35212267312543 13513 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 2; use IO::All; use IO_All_Test; my $io = io('t/scalar.t'); my @list = $io->scalar; ok(@list == 1); test_file_contents($list[0], 't/scalar.t'); del_output_dir(); append.t100644001750001750 237312267312543 13542 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More; use IO::All; use IO_All_Test; plan((lc($^O) eq 'mswin32' and defined $ENV{PERL5_CPANPLUS_IS_RUNNING}) ? (skip_all => "CPANPLUS/MSWin32 breaks this") : ($] < 5.008003) ? (skip_all => 'Broken on older perls') : (tests => 4) ); { my $log = io->file(o_dir() . "/myappend.txt")->mode('>>')->open(); $log->print("Hello World!\n"); $log->close(); } { # TEST ok (scalar(-f o_dir() . "/myappend.txt"), "myappend.txt exists."); my $contents = _slurp(o_dir() . "/myappend.txt"); # TEST is ($contents, "Hello World!\n", "contents of the file are OK."); } { my $log = io->file(o_dir() . "/myappend.txt")->mode('>>')->open(); $log->print("Message No. 2!\n"); $log->close(); } { # TEST ok (scalar(-f o_dir() . "/myappend.txt"), "myappend.txt exists."); my $contents = _slurp(o_dir() . "/myappend.txt"); # TEST is ($contents, "Hello World!\nMessage No. 2!\n", "Second append was ok."); } sub _slurp { my $filename = shift; open my $in, "<", $filename or die "Cannot open '$filename' for slurping - $!"; local $/; my $contents = <$in>; close($in); return $contents; } del_output_dir(); assert.t100644001750001750 136312267312543 13572 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 8; use IO::All; use IO_All_Test; use Cwd qw(getcwd); { ok(not -e o_dir() . '/newpath/hello.txt'); ok(not -e o_dir() . '/newpath'); my $io = io(o_dir() . '/newpath/hello.txt')->assert; ok(not -e o_dir() . '/newpath'); "Hello\n" > $io; ok(-f o_dir() . '/newpath/hello.txt'); } { my $orig_path = getcwd(); chdir(o_dir() . '/newpath'); # Bug http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=733680 "Hello" > io->file('foobar')->assert; ok( -f 'foobar'); is( scalar (-s 'foobar'), 5); "12345678" > io->file('./1_8')->assert; ok( -f '1_8', "Dot-slash-assert."); is( scalar (-s '1_8'), 8, "Size is 8."); chdir($orig_path); } del_output_dir(); method_list100644001750001750 340112267312543 14072 0ustar00frewfrew000000000000IO-All-0.54C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, text.utf8100644001750001750 17512267312543 13660 0ustar00frewfrew000000000000IO-All-0.54/tWe are noticing that our Big5 greeting --- 你好, 我是貝爾實驗室的中文語音合成系統 --- is being garbled in text.big5100644001750001750 15312267312543 13614 0ustar00frewfrew000000000000IO-All-0.54/tWe are noticing that our Big5 greeting --- An, ڬOǪyXt --- is being garbled in assert2.t100644001750001750 75412267312543 13637 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 4; use IO::All; use IO_All_Test; ok(io(o_dir() . '/xxx/yyy/zzz.db')->dbm->assert->{foo} = "bar"); ok(-f o_dir() . '/xxx/yyy/zzz.db' or -f o_dir() . '/xxx/yyy/zzz.db.dir'); SKIP: { skip "requires MLDBM", 2 unless eval { require MLDBM; 1}; ok(io(o_dir() . '/xxx/yyy/zzz2.db')->assert->mldbm->{foo} = ["bar"]); ok(-f o_dir() . '/xxx/yyy/zzz2.db' or -f o_dir() . '/xxx/yyy/zzz.db.dir'); } del_output_dir(); autotie.t100644001750001750 53612267312543 13724 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use File::Spec::Functions; use Test::More; use IO::All; use IO_All_Test; my $f = catfile('t', 'mystuff'); my @lines = read_file_lines($f); plan(tests => 1 + @lines + 1); my $io = io($f)->tie; is($io->autoclose(0) . '', $f); while (<$io>) { is($_, shift @lines); } ok(close $io); del_output_dir(); RT81224.t100644001750001750 33412267312543 13174 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't'; use strict; use warnings; use Test::More tests => 1; use IO::All -utf8; my $warnings = 0; $SIG{__WARN__} = sub { $warnings++ }; my $img = io('t/img.jpg')->binary->all; ok(!$warnings, 'no unicode warnings'); devnull.t100644001750001750 26312267312543 13720 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 2; use IO::All; use IO_All_Test; ok("xxx" > io->devnull); ok(io->devnull->print("yyy")); del_output_dir(); println.t100644001750001750 50212267312543 13731 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 1; use IO::All; use IO_All_Test; my $io = io('t/println.t'); my @lines = map {chomp; $_} $io->slurp; my $temp = io('?'); $temp->println(@lines); $temp->seek(0, 0); my $text = $temp->slurp; test_file_contents($text, 't/println.t'); del_output_dir(); morestuff100644001750001750 5012267312543 13771 0ustar00frewfrew000000000000IO-All-0.54/tMore stuff is pure fluff. Off the cuff. unit000755001750001750 012267312543 12455 5ustar00frewfrew000000000000IO-All-0.54xxx.pl100644001750001750 40612267312543 13761 0ustar00frewfrew000000000000IO-All-0.54/unitBEGIN {$^W = 1} use strict; use IO::All; # Copy STDIN to a String File one paragraph at a time my $stdin = io('-'); my $string_out = io('$'); while (my $paragraph = $stdin->getline('')) { $string_out->print($paragraph); } print ${$string_out->string_ref}; Makefile.PL100644001750001750 163712267312543 13617 0ustar00frewfrew000000000000IO-All-0.54 use strict; use warnings; use ExtUtils::MakeMaker 6.30; my %WriteMakefileArgs = ( "ABSTRACT" => "IO::All of it to Graham and Damian!", "AUTHOR" => "Ingy d\x{f6}t Net ", "BUILD_REQUIRES" => {}, "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => "6.30" }, "DISTNAME" => "IO-All", "EXE_FILES" => [], "LICENSE" => "perl", "NAME" => "IO::All", "PREREQ_PM" => { "IO::String" => "1.08" }, "TEST_REQUIRES" => {}, "VERSION" => "0.54", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "IO::String" => "1.08" ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); rt-41819.t100644001750001750 27012267312543 13356 0ustar00frewfrew000000000000IO-All-0.54/tuse Test::More; use IO::All; plan 'skip_all' unless -d '/dev'; plan tests => 1; my $io = io('/dev'); my $path; my $f = $path->name while ($path = $io->next()); pass 'It works now'; tie_file.t100644001750001750 72512267312543 14032 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More; use IO_All_Test; use IO::All; plan((eval {require Tie::File; 1}) ? (tests => 2) : (skip_all => "requires Tie::File") ); { (io(o_dir() . '/tie_file1') < io('t/tie_file.t'))->close; my $file = io(o_dir() . '/tie_file1')->rdonly; is($file->[-1], 'bar'); is($file->[-2], 'foo'); "foo\n" x 3 > io(o_dir() . '/tie_file2'); io(o_dir() . '/tie_file2')->[1] = 'bar'; } del_output_dir(); __END__ foo bar absolute.t100644001750001750 46712267312543 14073 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 3; use IO::All; use IO_All_Test; use diagnostics; my $io = io($0); $io->absolute; is("$io", File::Spec->rel2abs($0)); $io->relative; is($io->pathname, File::Spec->abs2rel($0)); ok(io('t')->absolute->next->is_absolute); del_output_dir(); overload.t100644001750001750 461512267312543 14107 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't'; #, 'lib'; use strict; use warnings; use Test::More tests => 24; use IO_All_Test; use IO::All; unlink(o_dir() . '/overload1'); unlink(o_dir() . '/overload2'); unlink(o_dir() . '/overload3'); my $data < io('t/mystuff'); test_file_contents($data, 't/mystuff'); my $data1 = $data; my $data2 = $data . $data; $data << io('t/mystuff'); is($data, $data2); $data < io('t/mystuff'); is($data, $data1); io('t/mystuff') > $data; test_file_contents($data, 't/mystuff'); io('t/mystuff') >> $data; is($data, $data2); io('t/mystuff') > $data; is($data, $data1); $data > io(o_dir() . '/overload1'); test_file_contents($data, o_dir() . '/overload1'); $data > io(o_dir() . '/overload1'); test_file_contents($data, o_dir() . '/overload1'); $data >> io(o_dir() . '/overload1'); test_file_contents($data2, o_dir() . '/overload1'); io(o_dir() . '/overload1') < $data; test_file_contents($data, o_dir() . '/overload1'); io(o_dir() . '/overload1') < $data; test_file_contents($data, o_dir() . '/overload1'); io(o_dir() . '/overload1') << $data; test_file_contents($data2, o_dir() . '/overload1'); $data > io(o_dir() . '/overload1'); test_file_contents($data, o_dir() . '/overload1'); io(o_dir() . '/overload1') > io(o_dir() . '/overload2'); test_matching_files(o_dir() . '/overload1', o_dir() . '/overload2'); io(o_dir() . '/overload3') < io(o_dir() . '/overload2'); test_matching_files(o_dir() . '/overload1', o_dir() . '/overload3'); io(o_dir() . '/overload3') << io(o_dir() . '/overload2'); io(o_dir() . '/overload1') >> io(o_dir() . '/overload2'); test_matching_files(o_dir() . '/overload2', o_dir() . '/overload3'); test_file_contents($data2, o_dir() . '/overload3'); is(io('foo') . '', 'foo'); is("@{io 't/mydir'}", flip_slash 't/mydir/dir1 t/mydir/dir2 t/mydir/file1 t/mydir/file2 t/mydir/file3', ); is(join(' ', sort keys %{io 't/mydir'}), 'dir1 dir2 file1 file2 file3', ); is(join(' ', sort map {"$_"} values %{io 't/mydir'}), flip_slash 't/mydir/dir1 t/mydir/dir2 t/mydir/file1 t/mydir/file2 t/mydir/file3', ); ${io('t/mystuff')} . ${io('t/mystuff')} > io(o_dir() . '/overload1'); test_file_contents2(o_dir() . '/overload1', $data2); ${io('t/mystuff')} . "xxx\n" . ${io('t/mystuff')} > io(o_dir() . '/overload1'); $data < io('t/mystuff'); my $cat3 = $data . "xxx\n" . $data; test_file_contents2(o_dir() . '/overload1', $cat3); is "" . ${io("t")}, "t", "scalar overload of directory (for mst)"; del_output_dir(); in-place.t100644001750001750 113312267312543 13754 0ustar00frewfrew000000000000IO-All-0.54/t#!/usr/bin/perl use strict; use warnings; use Test::More tests => 5; use IO::All; use File::Temp qw/tempdir/; { my $tempdir = tempdir( CLEANUP => 1); my $f = sub { return io->catfile($tempdir, 'test.txt') }; $f->()->print(<<'EOF'); #One #Two #Three #Four EOF # Test that the array overloading of IO::All can be modified to # produce new contents. foreach my $line (@{$f->()}) { # TEST*4 ok (($line =~ s{\A#}{}), 'Done substitution.'); } # TEST is (scalar($f->()->slurp()), <<'EOF', 'File contents were modified.'); One Two Three Four EOF } encoding.t100644001750001750 164412267312543 14061 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More; use IO_All_Test; BEGIN { eval { require PerlIO::encoding }; plan(skip_all => 'no PerlIO::encoding') if $@; plan(($] < 5.008003) ? (skip_all => 'Broken on older perls') : (tests => 4) ); } package Normal; use IO::All; package UTF8; use IO::All -utf8; package Big5; use IO::All -encoding => 'big5'; package main; isnt Normal::io('t/text.big5')->all, Normal::io('t/text.utf8')->all, 'big5 and utf8 tests are different'; isnt Normal::io('t/text.big5')->all, Big5::io('t/text.big5')->all, 'Read big5 with different io-s does not match'; is UTF8::io('t/text.utf8')->all, Big5::io('t/text.big5')->all, 'Big5 text matches utf8 text after read'; is Normal::io('t/text.utf8')->utf8->all, Normal::io('t/text.big5')->encoding('big5')->all, 'Big5 text matches utf8 text after read'; del_output_dir(); test.pl100644001750001750 6412267312543 14071 0ustar00frewfrew000000000000IO-All-0.54/unituse strict; use lib 'lib'; use IO::All; io('xxx'); IO000755001750001750 012267312543 12553 5ustar00frewfrew000000000000IO-All-0.54/libAll.pm100755001750001750 5316212267312543 14013 0ustar00frewfrew000000000000IO-All-0.54/lib/IOpackage IO::All; use 5.006001; use strict; use warnings; require Carp; # So one can use Carp::carp "$message" - without the parenthesis. sub Carp::carp; use IO::All::Base -base; use File::Spec(); use Symbol(); use Fcntl; # ABSTRACT: IO::All of it to Graham and Damian! our $VERSION = '0.54'; # VERSION our @EXPORT = qw(io); #=============================================================================== # Object creation and setup methods #=============================================================================== my $autoload = { qw( touch file dir_handle dir All dir all_files dir All_Files dir all_dirs dir All_Dirs dir all_links dir All_Links dir mkdir dir mkpath dir next dir stdin stdio stdout stdio stderr stdio socket_handle socket accept socket shutdown socket readlink link symlink link ) }; # XXX - These should die if the given argument exists but is not a # link, dbm, etc. sub link {my $self = shift; require IO::All::Link; IO::All::Link::link($self, @_) } sub dbm {my $self = shift; require IO::All::DBM; IO::All::DBM::dbm($self, @_) } sub mldbm {my $self = shift; require IO::All::MLDBM; IO::All::MLDBM::mldbm($self, @_) } sub autoload {my $self = shift; $autoload } sub AUTOLOAD { my $self = shift; my $method = $IO::All::AUTOLOAD; $method =~ s/.*:://; my $pkg = ref($self) || $self; $self->throw(qq{Can't locate object method "$method" via package "$pkg"}) if $pkg ne $self->package; my $class = $self->autoload_class($method); my $foo = "$self"; bless $self, $class; $self->$method(@_); } sub autoload_class { my $self = shift; my $method = shift; my $class_id = $self->autoload->{$method} || $method; my $ucfirst_class_name = 'IO::All::' . ucfirst($class_id); my $ucfirst_class_fn = "IO/All/" . ucfirst($class_id) . ".pm"; return $ucfirst_class_name if $INC{$ucfirst_class_fn}; return "IO::All::\U$class_id" if $INC{"IO/All/\U$class_id\E.pm"}; require IO::All::Temp; if (eval "require $ucfirst_class_name; 1") { my $class = $ucfirst_class_name; my $return = $class->can('new') ? $class : do { # (OS X hack) my $value = $INC{$ucfirst_class_fn}; delete $INC{$ucfirst_class_fn}; $INC{"IO/All/\U$class_id\E.pm"} = $value; "IO::All::\U$class_id"; }; return $return; } elsif (eval "require IO::All::\U$class_id; 1") { return "IO::All::\U$class_id"; } $self->throw("Can't find a class for method '$method'"); } sub new { my $self = shift; my $package = ref($self) || $self; my $new = bless Symbol::gensym(), $package; $new->package($package); $new->_copy_from($self) if ref($self); my $name = shift; return $name if UNIVERSAL::isa($name, 'IO::All'); return $new->_init unless defined $name; return $new->handle($name) if UNIVERSAL::isa($name, 'GLOB') or ref(\ $name) eq 'GLOB'; # WWW - link is first because a link to a dir returns true for # both -l and -d. return $new->link($name) if -l $name; return $new->file($name) if -f $name; return $new->dir($name) if -d $name; return $new->$1($name) if $name =~ /^([a-z]{3,8}):/; return $new->socket($name) if $name =~ /^[\w\-\.]*:\d{1,5}$/; return $new->pipe($name) if $name =~ s/^\s*\|\s*// or $name =~ s/\s*\|\s*$//; return $new->string if $name eq '$'; return $new->stdio if $name eq '-'; return $new->stderr if $name eq '='; return $new->temp if $name eq '?'; $new->name($name); $new->_init; } sub _copy_from { my $self = shift; my $other = shift; for (keys(%{*$other})) { # XXX Need to audit exclusions here next if /^(_handle|io_handle|is_open)$/; *$self->{$_} = *$other->{$_}; } } sub handle { my $self = shift; $self->_handle(shift) if @_; return $self->_init; } #=============================================================================== # Tie Interface #=============================================================================== sub tie { my $self = shift; tie *$self, $self; return $self; } sub TIEHANDLE { return $_[0] if ref $_[0]; my $class = shift; my $self = bless Symbol::gensym(), $class; $self->init(@_); } sub READLINE { goto &getlines if wantarray; goto &getline; } sub DESTROY { my $self = shift; no warnings; unless ( $] < 5.008 ) { untie *$self if tied *$self; } $self->close if $self->is_open; } sub BINMODE { my $self = shift; binmode *$self->io_handle; } { no warnings; *GETC = \&getc; *PRINT = \&print; *PRINTF = \&printf; *READ = \&read; *WRITE = \&write; *SEEK = \&seek; *TELL = \&getpos; *EOF = \&eof; *CLOSE = \&close; *FILENO = \&fileno; } #=============================================================================== # Overloading support #=============================================================================== my $old_warn_handler = $SIG{__WARN__}; $SIG{__WARN__} = sub { if ($_[0] !~ /^Useless use of .+ \(.+\) in void context/) { goto &$old_warn_handler if $old_warn_handler; warn(@_); } }; use overload '""' => 'overload_stringify'; use overload '|' => 'overload_bitwise_or'; use overload '<<' => 'overload_left_bitshift'; use overload '>>' => 'overload_right_bitshift'; use overload '<' => 'overload_less_than'; use overload '>' => 'overload_greater_than'; use overload '${}' => 'overload_string_deref'; use overload '@{}' => 'overload_array_deref'; use overload '%{}' => 'overload_hash_deref'; use overload '&{}' => 'overload_code_deref'; sub overload_bitwise_or {my $self = shift; $self->overload_handler(@_, '|') } sub overload_left_bitshift {my $self = shift; $self->overload_handler(@_, '<<') } sub overload_right_bitshift {my $self = shift; $self->overload_handler(@_, '>>') } sub overload_less_than {my $self = shift; $self->overload_handler(@_, '<') } sub overload_greater_than {my $self = shift; $self->overload_handler(@_, '>') } sub overload_string_deref {my $self = shift; $self->overload_handler(@_, '${}') } sub overload_array_deref {my $self = shift; $self->overload_handler(@_, '@{}') } sub overload_hash_deref {my $self = shift; $self->overload_handler(@_, '%{}') } sub overload_code_deref {my $self = shift; $self->overload_handler(@_, '&{}') } sub overload_handler { my ($self) = @_; my $method = $self->get_overload_method(@_); $self->$method(@_); } my $op_swap = { '>' => '<', '>>' => '<<', '<' => '>', '<<' => '>>', }; sub overload_table { my $self = shift; ( '* > *' => 'overload_any_to_any', '* < *' => 'overload_any_from_any', '* >> *' => 'overload_any_addto_any', '* << *' => 'overload_any_addfrom_any', '* < scalar' => 'overload_scalar_to_any', '* > scalar' => 'overload_any_to_scalar', '* << scalar' => 'overload_scalar_addto_any', '* >> scalar' => 'overload_any_addto_scalar', ) }; sub get_overload_method { my ($self, $arg1, $arg2, $swap, $operator) = @_; if ($swap) { $operator = $op_swap->{$operator} || $operator; } my $arg1_type = $self->get_argument_type($arg1); my $table1 = { $arg1->overload_table }; if ($operator =~ /\{\}$/) { my $key = "$operator $arg1_type"; return $table1->{$key} || $self->overload_undefined($key); } my $arg2_type = $self->get_argument_type($arg2); my @table2 = UNIVERSAL::isa($arg2, "IO::All") ? ($arg2->overload_table) : (); my $table = { %$table1, @table2 }; my @keys = ( "$arg1_type $operator $arg2_type", "* $operator $arg2_type", ); push @keys, "$arg1_type $operator *", "* $operator *" unless $arg2_type =~ /^(scalar|array|hash|code|ref)$/; for (@keys) { return $table->{$_} if defined $table->{$_}; } return $self->overload_undefined($keys[0]); } sub get_argument_type { my $self = shift; my $argument = shift; my $ref = ref($argument); return 'scalar' unless $ref; return 'code' if $ref eq 'CODE'; return 'array' if $ref eq 'ARRAY'; return 'hash' if $ref eq 'HASH'; return 'ref' unless $argument->isa('IO::All'); $argument->file if defined $argument->pathname and not $argument->type; return $argument->type || 'unknown'; } sub overload_stringify { my $self = shift; my $name = $self->pathname; return defined($name) ? $name : overload::StrVal($self); } sub overload_undefined { my $self = shift; require Carp; my $key = shift; Carp::carp "Undefined behavior for overloaded IO::All operation: '$key'" if $^W; return 'overload_noop'; } sub overload_noop { my $self = shift; return; } sub overload_any_addfrom_any { $_[1]->append($_[2]->all); $_[1]; } sub overload_any_addto_any { $_[2]->append($_[1]->all); $_[2]; } sub overload_any_from_any { $_[1]->close if $_[1]->is_file and $_[1]->is_open; $_[1]->print($_[2]->all); $_[1]; } sub overload_any_to_any { $_[2]->close if $_[2]->is_file and $_[2]->is_open; $_[2]->print($_[1]->all); $_[2]; } sub overload_any_to_scalar { $_[2] = $_[1]->all; } sub overload_any_addto_scalar { $_[2] .= $_[1]->all; $_[2]; } sub overload_scalar_addto_any { $_[1]->append($_[2]); $_[1]; } sub overload_scalar_to_any { local $\; $_[1]->close if $_[1]->is_file and $_[1]->is_open; $_[1]->print($_[2]); $_[1]; } #=============================================================================== # Private Accessors #=============================================================================== field 'package'; field _binary => undef; field _binmode => undef; field _strict => undef; field _encoding => undef; field _utf8 => undef; field _handle => undef; #=============================================================================== # Public Accessors #=============================================================================== field constructor => undef; chain block_size => 1024; chain errors => undef; field io_handle => undef; field is_open => 0; chain mode => undef; chain name => undef; chain perms => undef; chain separator => $/; field type => ''; field _partial_spec_class => undef; sub _spec_class { my $self = shift; my $ret = 'File::Spec'; if (my $partial = $self->_partial_spec_class(@_)) { $ret .= '::' . $partial; eval "require $ret"; } return $ret } sub pathname {my $self = shift; $self->name(@_) } #=============================================================================== # Chainable option methods (write only) #=============================================================================== option 'assert'; option 'autoclose' => 1; option 'backwards'; option 'chomp'; option 'confess'; option 'lock'; option 'rdonly'; option 'rdwr'; option 'strict'; #=============================================================================== # IO::Handle proxy methods #=============================================================================== proxy 'autoflush'; proxy 'eof'; proxy 'fileno'; proxy 'stat'; proxy 'tell'; proxy 'truncate'; #=============================================================================== # IO::Handle proxy methods that open the handle if needed #=============================================================================== proxy_open print => '>'; proxy_open printf => '>'; proxy_open sysread => O_RDONLY; proxy_open syswrite => O_CREAT | O_WRONLY; proxy_open seek => $^O eq 'MSWin32' ? '<' : '+<'; proxy_open 'getc'; #=============================================================================== # File::Spec Interface #=============================================================================== sub canonpath {my $self = shift; File::Spec->canonpath($self->pathname) } sub catdir { my $self = shift; my @args = grep defined, $self->name, @_; $self->constructor->()->dir(File::Spec->catdir(@args)); } sub catfile { my $self = shift; my @args = grep defined, $self->name, @_; $self->constructor->()->file(File::Spec->catfile(@args)); } sub join {my $self = shift; $self->catfile(@_) } sub curdir { my $self = shift; $self->constructor->()->dir(File::Spec->curdir); } sub devnull { my $self = shift; $self->constructor->()->file(File::Spec->devnull); } sub rootdir { my $self = shift; $self->constructor->()->dir(File::Spec->rootdir); } sub tmpdir { my $self = shift; $self->constructor->()->dir(File::Spec->tmpdir); } sub updir { my $self = shift; $self->constructor->()->dir(File::Spec->updir); } sub case_tolerant { my $self = shift; File::Spec->case_tolerant; } sub is_absolute { my $self = shift; File::Spec->file_name_is_absolute($self->pathname); } sub path { my $self = shift; map { $self->constructor->()->dir($_) } File::Spec->path; } sub splitpath { my $self = shift; File::Spec->splitpath($self->pathname); } sub splitdir { my $self = shift; File::Spec->splitdir($self->pathname); } sub catpath { my $self = shift; $self->constructor->(File::Spec->catpath(@_)); } sub abs2rel { my $self = shift; File::Spec->abs2rel($self->pathname, @_); } sub rel2abs { my $self = shift; File::Spec->rel2abs($self->pathname, @_); } #=============================================================================== # Public IO Action Methods #=============================================================================== sub absolute { my $self = shift; $self->pathname(File::Spec->rel2abs($self->pathname)) unless $self->is_absolute; $self->is_absolute(1); return $self; } sub all { my $self = shift; $self->assert_open('<'); local $/; my $all = $self->io_handle->getline; $self->error_check; $self->_autoclose && $self->close; return $all; } sub append { my $self = shift; $self->assert_open('>>'); $self->print(@_); } sub appendln { my $self = shift; $self->assert_open('>>'); $self->println(@_); } sub binary { my $self = shift; binmode($self->io_handle) if $self->is_open; $self->_binary(1); $self->encoding(0); return $self; } sub binmode { my $self = shift; my $layer = shift; if ($self->is_open) { $layer ? CORE::binmode($self->io_handle, $layer) : CORE::binmode($self->io_handle); } $self->_binmode($layer); return $self; } sub buffer { my $self = shift; if (not @_) { *$self->{buffer} = do {my $x = ''; \ $x} unless exists *$self->{buffer}; return *$self->{buffer}; } my $buffer_ref = ref($_[0]) ? $_[0] : \ $_[0]; $$buffer_ref = '' unless defined $$buffer_ref; *$self->{buffer} = $buffer_ref; return $self; } sub clear { my $self = shift; my $buffer = *$self->{buffer}; $$buffer = ''; return $self; } sub close { my $self = shift; return unless $self->is_open; $self->is_open(0); my $io_handle = $self->io_handle; $self->io_handle(undef); $self->mode(undef); $io_handle->close(@_) if defined $io_handle; return $self; } sub empty { my $self = shift; my $message = "Can't call empty on an object that is neither file nor directory"; $self->throw($message); } sub exists {my $self = shift; -e $self->pathname } sub getline { my $self = shift; return $self->getline_backwards if $self->_backwards; $self->assert_open('<'); my $line; { local $/ = @_ ? shift(@_) : $self->separator; $line = $self->io_handle->getline; chomp($line) if $self->_chomp and defined $line; } $self->error_check; return $line if defined $line; $self->close if $self->_autoclose; return undef; } sub getlines { my $self = shift; return $self->getlines_backwards if $self->_backwards; $self->assert_open('<'); my @lines; { local $/ = @_ ? shift(@_) : $self->separator; @lines = $self->io_handle->getlines; if ($self->_chomp) { chomp for @lines; } } $self->error_check; return @lines if @lines; $self->close if $self->_autoclose; return (); } sub is_dir {my $self = shift; UNIVERSAL::isa($self, 'IO::All::Dir') } sub is_dbm {my $self = shift; UNIVERSAL::isa($self, 'IO::All::DBM') } sub is_file {my $self = shift; UNIVERSAL::isa($self, 'IO::All::File') } sub is_link {my $self = shift; UNIVERSAL::isa($self, 'IO::All::Link') } sub is_mldbm {my $self = shift; UNIVERSAL::isa($self, 'IO::All::MLDBM') } sub is_socket {my $self = shift; UNIVERSAL::isa($self, 'IO::All::Socket') } sub is_stdio {my $self = shift; UNIVERSAL::isa($self, 'IO::All::STDIO') } sub is_string {my $self = shift; UNIVERSAL::isa($self, 'IO::All::String') } sub is_temp {my $self = shift; UNIVERSAL::isa($self, 'IO::All::Temp') } sub length { my $self = shift; length(${$self->buffer}); } sub open { my $self = shift; return $self if $self->is_open; $self->is_open(1); my ($mode, $perms) = @_; $self->mode($mode) if defined $mode; $self->mode('<') unless defined $self->mode; $self->perms($perms) if defined $perms; my @args; unless ($self->is_dir) { push @args, $self->mode; push @args, $self->perms if defined $self->perms; } if (defined $self->pathname and not $self->type) { $self->file; return $self->open(@args); } elsif (defined $self->_handle and not $self->io_handle->opened ) { # XXX Not tested $self->io_handle->fdopen($self->_handle, @args); } $self->set_binmode; } sub println { my $self = shift; $self->print(map {/\n\z/ ? ($_) : ($_, "\n")} @_); } sub read { my $self = shift; $self->assert_open('<'); my $length = (@_ or $self->type eq 'dir') ? $self->io_handle->read(@_) : $self->io_handle->read( ${$self->buffer}, $self->block_size, $self->length, ); $self->error_check; return $length || $self->_autoclose && $self->close && 0; } { no warnings; *readline = \&getline; } # deprecated sub scalar { my $self = shift; $self->all(@_); } sub slurp { my $self = shift; my $slurp = $self->all; return $slurp unless wantarray; my $separator = $self->separator; if ($self->_chomp) { local $/ = $separator; map {chomp; $_} split /(?<=\Q$separator\E)/, $slurp; } else { split /(?<=\Q$separator\E)/, $slurp; } } sub utf8 { my $self = shift; if ($] < 5.008) { die "IO::All -utf8 not supported on Perl older than 5.8"; } CORE::binmode($self->io_handle, ':encoding(UTF-8)') if $self->is_open; $self->_utf8(1); $self->encoding('utf8'); return $self; } sub encoding { my $self = shift; my $encoding = shift; if ($] < 5.008) { die "IO::All -encoding not supported on Perl older than 5.8"; } CORE::binmode($self->io_handle, ":encoding($encoding)") if $self->is_open; $self->_encoding($encoding); return $self; } sub write { my $self = shift; $self->assert_open('>'); my $length = @_ ? $self->io_handle->write(@_) : $self->io_handle->write(${$self->buffer}, $self->length); $self->error_check; $self->clear unless @_; return $length; } #=============================================================================== # Implementation methods. Subclassable. #=============================================================================== sub throw { my $self = shift; require Carp; ; return &{$self->errors}(@_) if $self->errors; return Carp::confess(@_) if $self->_confess; return Carp::croak(@_); } #=============================================================================== # Private instance methods #=============================================================================== sub assert_dirpath { my $self = shift; my $dir_name = shift; return $dir_name if ((! CORE::length($dir_name)) or -d $dir_name or CORE::mkdir($dir_name, $self->perms || 0755) or do { require File::Path; File::Path::mkpath($dir_name, 0, $self->perms || 0755 ); } or $self->throw("Can't make $dir_name")); } sub assert_open { my $self = shift; return if $self->is_open; $self->file unless $self->type; return $self->open(@_); } sub error_check { my $self = shift; return unless $self->io_handle->can('error'); return unless $self->io_handle->error; $self->throw($!); } sub copy { my $self = shift; my $copy; for (keys %{*$self}) { $copy->{$_} = *$self->{$_}; } $copy->{io_handle} = 'defined' if defined $copy->{io_handle}; return $copy; } sub set_binmode { my $self = shift; if (my $encoding = $self->_encoding) { CORE::binmode($self->io_handle, ":encoding($encoding)"); } elsif ($self->_binary) { CORE::binmode($self->io_handle); } elsif ($self->_binmode) { CORE::binmode($self->io_handle, $self->_binmode); } return $self; } #=============================================================================== # Stat Methods #=============================================================================== BEGIN { no strict 'refs'; my @stat_fields = qw( device inode modes nlink uid gid device_id size atime mtime ctime blksize blocks ); foreach my $stat_field_idx (0 .. $#stat_fields) { my $idx = $stat_field_idx; my $name = $stat_fields[$idx]; *$name = sub { my $self = shift; return (stat($self->io_handle || $self->pathname))[$idx]; }; } } file_spec.t100644001750001750 1001712267312543 14236 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 31; use IO::All; use IO_All_Test; is(io('././t/file_spec.t')->canonpath, f 't/file_spec.t'); is(io('././t/file_spec.t')->ext, 't'); is(io('././t/file_spec.t')->extension, 't'); is(io('././t/bogus')->canonpath, f 't/bogus'); is(join(';', grep {! /CVS|\.svn/} io->catdir(qw(t mydir))->all), f 't/mydir/dir1;t/mydir/dir2;t/mydir/file1;t/mydir/file2;t/mydir/file3'); test_file_contents(io->catfile(qw(t mystuff))->scalar, 't/mystuff'); test_file_contents(io->join(qw(t mystuff))->scalar, 't/mystuff'); is(ref(io->devnull), 'IO::All::File'); ok(io->devnull->print('IO::All')); # Not supporting class calls anymore. Objects only. # ok(IO::All->devnull->print('IO::All')); ok(io->rootdir->is_dir); ok(io->tmpdir->is_dir); ok(io->updir->is_dir); like(io->case_tolerant, qr/^[01]$/); ok(io('/foo/bar')->is_absolute); ok(not io('foo/bar')->is_absolute); { # if this fails on other OSes more examples for PATH will need to be made local $ENV{PATH} = $^O eq 'MSWin32' ? 'C:\PROGRAM FILES\COMMON FILES\MICROSOFT SHARED\WINDOWS LIVE;C:\PROGRAM FILES (X86)\COMMON FILES\MICROSOFT SHARED\WINDOWS LIVE;C:\PROGRAM FILES (X86)\INTEL\ICLS CLIENT\;C:\PROGRAM FILES\INTEL\ICLS CLIENT\;C:\Windows\SYSTEM32;C:\Windows;C:\Windows\SYSTEM32\WBEM;C:\Windows\SYSTEM32\WINDOWSPOWERSHELL\V1.0\;;C:\PROGRAM FILES (X86)\INTEL\OPENCL SDK\2.0\BIN\X86;C:\PROGRAM FILES (X86)\INTEL\OPENCL SDK\2.0\BIN\X64;C:\PROGRAM FILES\COMMON FILES\LENOVO;C:\PROGRAM FILES (X86)\WINDOWS LIVE\SHARED;C:\PROGRAM FILES (X86)\LENOVO\ACCESS CONNECTIONS\;C:\SWTOOLS\READYAPPS;C:\PROGRAM FILES (X86)\SYMANTEC\VIP ACCESS CLIENT\;C:\PROGRAM FILES (X86)\COMMON FILES\LENOVO;C:\PROGRAM FILES\INTEL\INTEL(R) MANAGEMENT ENGINE COMPONENTS\DAL;C:\PROGRAM FILES\INTEL\INTEL(R) MANAGEMENT ENGINE COMPONENTS\IPT;C:\PROGRAM FILES (X86)\INTEL\INTEL(R) MANAGEMENT ENGINE COMPONENTS\DAL;C:\PROGRAM FILES (X86)\INTEL\INTEL(R) MANAGEMENT ENGINE COMPONENTS\IPT;C:\PROGRAM FILES\INTEL\WIFI\BIN\;C:\PROGRAM FILES\COMMON FILES\INTEL\WIRELESSCOMMON\;C:\Program Files\ThinkPad\Bluetooth Software\;C:\Program Files\ThinkPad\Bluetooth Software\syswow64;C:\Program Files\MiKTeX 2.9\miktex\bin\x64\;C:\Dwimperl\perl\bin;C:\Dwimperl\perl\site\bin;C:\Dwimperl\c\bin;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon' : '/home/frew/.plenv/bin:/home/frew/node/bin::/home/frew/code/git-super-status/bin:/opt/bin:/home/frew/code/teatime/bin:/home/frew/bin:/home/frew/code/dotfiles/bin:/home/frew/Dropbox/bin:/home/frew/Dropbox/go/bin:/home/frew/Dropbox/node/bin:/opt/bin:/home/frew/.plenv/bin:/home/frew/node/bin:/home/frew/code/git-super-status/bin:/opt/bin:/home/frew/code/teatime/bin:/home/frew/bin:/home/frew/code/dotfiles/bin:/home/frew/Dropbox/bin:/home/frew/Dropbox/go/bin:/home/frew/Dropbox/node/bin:/home/frew/.plenv/shims:/home/frew/perl5/perlbrew/bin:/home/frew/perl5/perlbrew/perls/perl-5.16.0/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/frew/.zsh/adenosine/bin:/home/frew/.zsh/adenosine/bin'; my $expected = $^O eq 'MSWin32' ? 31 : 36; my @path1 = io->path; is scalar( @path1 ), $expected, "expected amount of PATH entries returned"; } my ($v, $d, $f) = io('foo/bar')->splitpath; is($d, 'foo/'); is($f, 'bar'); my @dirs = io('foo/bar/baz')->splitdir; is(scalar(@dirs), 3); is(join('+', @dirs), 'foo+bar+baz'); test_file_contents(io->catpath('', qw(t mystuff))->scalar, 't/mystuff'); is(io('/foo/bar/baz')->abs2rel('/foo'), f 'bar/baz'); is(io('foo/bar/baz')->rel2abs('/moo'), f '/moo/foo/bar/baz'); is("".io->dir('doo/foo')->catdir('goo', 'hoo'), f 'doo/foo/goo/hoo'); is("".io->dir->catdir('goo', 'hoo'), f 'goo/hoo'); is("".io->catdir('goo', 'hoo'), f 'goo/hoo'); is("".io->file('doo/foo')->catfile('goo', 'hoo'), f 'doo/foo/goo/hoo'); is("".io->file->catfile('goo', 'hoo'), f 'goo/hoo'); is("".io->catfile('goo', 'hoo'), f 'goo/hoo'); is("".io->file('goo', 'hoo', 'bar.txt'), f 'goo/hoo/bar.txt'); is("".io->dir('goo', 'hoo'), f 'goo/hoo'); del_output_dir(); separator.t100644001750001750 60612267312543 14250 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 4; use IO::All; use IO_All_Test; join('', ) > io(o_dir() . '/separator1'); my $io = io(o_dir() . '/separator1'); $io->separator('t'); my @chunks = $io->slurp; is(scalar @chunks, 3); is($chunks[0], "one\nt"); is($chunks[1], "wo\nt"); is($chunks[2], "hree\nfour\n"); del_output_dir(); __DATA__ one two three four construct.t100644001750001750 225112267312543 14312 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 18; use IO::All; use IO_All_Test; my $io1 = IO::All->new('t/mystuff'); is(ref($io1), 'IO::All::File'); test_file_contents($$io1, 't/mystuff'); my $io2 = io('t/mystuff'); is(ref($io2), 'IO::All::File'); test_file_contents($$io2, 't/mystuff'); my $io3 = io->file('t/mystuff'); is(ref($io3), 'IO::All::File'); test_file_contents($$io3, 't/mystuff'); my $io4 = $io3->file('t/construct.t'); is(ref($io4), 'IO::All::File'); test_file_contents($$io4, 't/construct.t'); my $io5 = io->dir('t/mydir'); is(ref($io5), 'IO::All::Dir'); is(join('+', map $_->filename, grep {! /CVS|\.svn/} $io5->all), 'dir1+dir2+file1+file2+file3'); my $io6 = io->rdonly->new->file('t/construct.t'); ok($io6->_rdonly); SKIP: { eval {require Tie::File}; skip "requires Tie::File", 1 if $@; test_file_contents(join('', map {"$_\n"} @$io6), 't/construct.t'); } my $io7 = io->socket('foo.com:80')->get_socket_domain_port; ok($io7->is_socket); is($io7->domain, 'foo.com'); is($io7->port, '80'); my $io8 = io(':8000')->get_socket_domain_port; ok($io8->is_socket); is($io8->domain, 'localhost'); is($io8->port, '8000'); del_output_dir(); synopsis2.t100644001750001750 144412267312543 14242 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 10; use IO::All; use IO_All_Test; # Print name and first line of all files in a directory my $dir = io('t/mydir'); ok($dir->is_dir); my @results; while (my $io = $dir->next) { if ($io->is_file) { push @results, $io->name . ' - ' . $io->getline; } } for my $line (sort @results) { is($line, flip_slash scalar ); } # Print name of all files recursively is("$_\n", flip_slash scalar ) for sort {$a->name cmp $b->name} grep {! /CVS|\.svn/} io('t/mydir')->all_files(0); del_output_dir(); __END__ t/mydir/file1 - file1 is fun t/mydir/file2 - file2 is woohoo t/mydir/file3 - file3 is whee t/mydir/dir1/dira/dirx/file1 t/mydir/dir1/file1 t/mydir/dir2/file1 t/mydir/file1 t/mydir/file2 t/mydir/file3 synopsis5.t100644001750001750 51512267312543 14223 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 3; use IO::All; # Write some data to a temporary file and retrieve all the paragraphs. my $data = io('t/synopsis5.t')->slurp; my $temp = io->temp; ok($temp->print($data)); ok($temp->seek(0, 0)); my @paragraphs = $temp->getlines(''); is(scalar @paragraphs, 4); backwards.t100644001750001750 101712267312543 14226 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More; use IO::All; use IO_All_Test; plan((eval {require File::ReadBackwards; 1}) ? (tests => 2) : (skip_all => "requires File::ReadBackwards") ); my @reversed; my $io = io('t/mystuff'); $io->backwards; while (my $line = $io->getline) { push @reversed, $line; } test_file_contents(join('', reverse @reversed), 't/mystuff'); @reversed = io('t/mystuff')->backwards->getlines; test_file_contents(join('', reverse @reversed), 't/mystuff'); del_output_dir(); synopsis3.t100644001750001750 277012267312543 14246 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More; use IO_All_Test; use Config; plan((eval {require IO::String; 1}) ? (tests => 3) : (skip_all => "requires IO::String") ); sub fix { local $_ = shift; if ($^O eq 'MSWin32') { s/"/'/g; return qq{"$_"}; } return qq{'$_'}; } undef $/; # # Copy STDIN to STDOUT # io('-')->print(io('-')->slurp); my $test1 = fix 'io("-")->print(io("-")->slurp)'; open TEST, '-|', qq{$^X -Ilib -MIO::All -e $test1 < t/mystuff} or die "open failed: $!"; test_file_contents(, 't/mystuff'); close TEST; # # Copy STDIN to STDOUT a block at a time # my $stdin = io('-'); # my $stdout = io('-'); # $stdout->buffer($stdin->buffer); # $stdout->write while $stdin->read; my $test2 = fix 'my $stdin = io("-");my $stdout = io("-");$stdout->buffer($stdin->buffer);$stdout->write while $stdin->read'; open TEST, '-|', qq{$^X -Ilib -MIO::All -e $test2 < t/mystuff} or die "open failed: $!"; test_file_contents(, 't/mystuff'); close TEST; # # Copy STDIN to a String File one line at a time # my $stdin = io('-'); # my $string_out = io('$'); # while (my $line = $stdin->getline) { # $string_out->print($line); # } my $test3 = fix 'my $stdin = io("-");my $string_out = io(q{$});while (my $line = $stdin->getline("")) {$string_out->print($line)} print ${$string_out->string_ref}'; open TEST, '-|', qq{$^X -Ilib -MIO::All -e $test3 < t/mystuff} or die "open failed: $!"; test_file_contents(, 't/mystuff'); close TEST; del_output_dir(); synopsis1.t100644001750001750 76412267312543 14225 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 6; use IO::All; use IO_All_Test; # Combine two files into a third my $my_stuff = io('t/mystuff')->slurp; test_file_contents($my_stuff, 't/mystuff'); my $more_stuff << io('t/morestuff'); test_file_contents($more_stuff, 't/morestuff'); io('t/allstuff')->print($my_stuff, $more_stuff); ok(-f 't/allstuff'); ok(-s 't/allstuff'); test_file_contents($my_stuff . $more_stuff, 't/allstuff'); ok(unlink('t/allstuff')); del_output_dir(); mydir000755001750001750 012267312543 13065 5ustar00frewfrew000000000000IO-All-0.54/tfile3100644001750001750 2112267312543 14103 0ustar00frewfrew000000000000IO-All-0.54/t/mydirfile3 is whee yo file2100644001750001750 2312267312543 14104 0ustar00frewfrew000000000000IO-All-0.54/t/mydirfile2 is woohoo yo file1100644001750001750 2012267312543 14100 0ustar00frewfrew000000000000IO-All-0.54/t/mydirfile1 is fun yo stdio.pl100644001750001750 17512267312543 14257 0ustar00frewfrew000000000000IO-All-0.54/unituse IO::All; my $stdin = io('-'); my $stdout = io('-'); $stdout->buffer($stdin->buffer); $stdout->write while $stdin->read; All.pod100644001750001750 13340512267312543 14175 0ustar00frewfrew000000000000IO-All-0.54/lib/IO=encoding utf8 =head1 NAME IO::All - IO::All of it to Graham and Damian! =head1 SYNOPSIS use IO::All; # Let the madness begin... # Some of the many ways to read a whole file into a scalar io('file.txt') > $contents; # Overloaded "arrow" $contents < io 'file.txt'; # Flipped but same operation $io = io 'file.txt'; # Create a new IO::All object $contents = $$io; # Overloaded scalar dereference $contents = $io->all; # A method to read everything $contents = $io->slurp; # Another method for that $contents = join '', $io->getlines; # Join the separate lines $contents = join '', map "$_\n", @$io; # Same. Overloaded array deref $io->tie; # Tie the object as a handle $contents = join '', <$io>; # And use it in builtins # and the list goes on ... # Other file operations: @lines = io('file.txt')->slurp; # List context slurp $content > io('file.txt'); # Print to a file io('file.txt')->print($content, $more); # (ditto) $content >> io('file.txt'); # Append to a file io('file.txt')->append($content); # (ditto) $content << $io; # Append to a string io('copy.txt') < io('file.txt'); $ Copy a file io('file.txt') > io('copy.txt'); # Invokes File::Copy io('more.txt') >> io('all.txt'); # Add on to a file # UTF-8 Support $contents = io('file.txt')->utf8->all; # Turn on utf8 use IO::All -utf8; # Turn on utf8 for all io $contents = io('file.txt')->all; # by default in this package. # General Encoding Support $contents = io('file.txt')->encoding('big5')->all; use IO::All -encoding => 'big5'; # Turn on big5 for all io $contents = io('file.txt')->all; # by default in this package. # Print the path name of a file: print $io->name; # The direct method print "$io"; # Object stringifies to name print $io; # Quotes not needed here print $io->filename; # The file portion only $io->os('win32'); # change the object to be a # win32 path print $io->ext; # The file extension only print $io->mimetype; # The mimetype, requires a # working File::MimeType # Read all the files/directories in a directory: $io = io('my/directory/'); # Create new directory object @contents = $io->all; # Get all contents of dir @contents = @$io; # Directory as an array @contents = values %$io; # Directory as a hash push @contents, $subdir # One at a time while $subdir = $io->next; # Print the name and file type for all the contents above: print "$_ is a " . $_->type . "\n" # Each element of @contents for @contents; # is an IO::All object!! # Print first line of each file: print $_->getline # getline gets one line for io('dir')->all_files; # Files only # Print names of all files/dirs three directories deep: print "$_\n" for $io->all(3); # Pass in the depth. Default=1 # Print names of all files/dirs recursively: print "$_\n" for $io->all(0); # Zero means all the way down print "$_\n" for $io->All; # Capitalized shortcut print "$_\n" for $io->deep->all; # Another way # There are some special file names: print io('-'); # Print STDIN to STDOUT io('-') > io('-'); # Do it again io('-') < io('-'); # Same. Context sensitive. "Bad puppy" > io('='); # Message to STDERR $string_file = io('$'); # Create IO::String Object $temp_file = io('?'); # Create a temporary file # Socket operations: $server = io('localhost:5555')->fork; # Create a daemon socket $connection = $server->accept; # Get a connection socket $input < $connection; # Get some data from it "Thank you!" > $connection; # Thank the caller $connection->close; # Hang up io(':6666')->accept->slurp > io->devnull; # Take a complaint and file it # DBM database operations: $dbm = io 'my/database'; # Create a database object print $dbm->{grocery_list}; # Hash context makes it a DBM $dbm->{todo} = $new_list; # Write to database $dbm->dbm('GDBM_file'); # Demand specific DBM io('mydb')->mldbm->{env} = \%ENV; # MLDBM support # Tie::File support: $io = io 'file.txt'; $io->[42] = 'Line Forty Three'; # Change a line print $io->[@$io / 2]; # Print middle line @$io = reverse @$io; # Reverse lines in a file # Stat functions: printf "%s %s %s\n", # Print name, uid and size of $_->name, $_->uid, $_->size # contents of current directory for io('.')->all; print "$_\n" for sort # Use mtime method to sort all {$b->mtime <=> $a->mtime} # files under current directory io('.')->All_Files; # by recent modification time. # File::Spec support: $contents < io->catfile(qw(dir file.txt)); # Portable IO operation # Miscellaneous: @lines = io('file.txt')->chomp->slurp; # Chomp as you slurp @chunks = io('file.txt')->separator('xxx')->slurp; # Use alternnate record sep $binary = io('file.bin')->binary->all; # Read a binary file io('a-symlink')->readlink->slurp; # Readlink returns an object print io('foo')->absolute->pathname; # Print absolute path of foo # IO::All External Plugin Methods io("myfile") > io->("ftp://store.org"); # Upload a file using ftp $html < io->http("www.google.com"); # Grab a web page io('mailto:worst@enemy.net')->print($spam); # Email a "friend" # This is just the beginning, read on... =head1 DESCRIPTION "Graham Barr for doing it all. Damian Conway for doing it all different." IO::All combines all of the best Perl IO modules into a single nifty object oriented interface to greatly simplify your everyday Perl IO idioms. It exports a single function called C, which returns a new IO::All object. And that object can do it all! The IO::All object is a proxy for IO::File, IO::Dir, IO::Socket, IO::String, Tie::File, File::Spec, File::Path, File::MimeInfo and File::ReadBackwards; as well as all the DBM and MLDBM modules. You can use most of the methods found in these classes and in IO::Handle (which they inherit from). IO::All adds dozens of other helpful idiomatic methods including file stat and manipulation functions. IO::All is pluggable, and modules like L and L add even more functionality. Optionally, every IO::All object can be tied to itself. This means that you can use most perl IO builtins on it: readline, <>, getc, print, printf, syswrite, sysread, close. The distinguishing magic of IO::All is that it will automatically open (and close) files, directories, sockets and other IO things for you. You never need to specify the mode ('<', '>>', etc), since it is determined by the usage context. That means you can replace this: open STUFF, '<', './mystuff' or die "Can't open './mystuff' for input:\n$!"; local $/; my $stuff = ; close STUFF; with this: my $stuff < io './mystuff'; And that is a B! =head1 USAGE Normally just say: use IO::All; and IO::All will export a single function called C, which constructs all IO objects. You can also pass global flags like this: use IO::All -encoding => 'big5', -foobar; Which automatically makes those method calls on every new IO object. In other words this: my $io = io('lalala.txt'); becomes this: my $io = io('lalala.txt')->encoding('big5')->foobar; =head1 METHOD ROLE CALL Here is an alphabetical list of all the public methods that you can call on an IO::All object. C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C and C. Each method is documented further below. =head1 OPERATOR OVERLOADING IO::All objects overload a small set of Perl operators to great effect. The overloads are limited to <, <<, >, >>, dereferencing operations, and stringification. Even though relatively few operations are overloaded, there is actually a huge matrix of possibilities for magic. That's because the overloading is sensitive to the types, position and context of the arguments, and an IO::All object can be one of many types. The most important overload to become familiar with is stringification. IO::All objects stringify to their file or directory name. Here we print the contents of the current directory: perl -MIO::All -le 'print for io(".")->all' is the same as: perl -MIO::All -le 'print $_->name for io(".")->all' Stringification is important because it allows IO::All operations to return objects when they might otherwise return file names. Then the recipient can use the result either as an object or a string. '>' and '<' move data between objects in the direction pointed to by the operator. $content1 < io('file1'); $content1 > io('file2'); io('file2') > $content3; io('file3') < $content3; io('file3') > io('file4'); io('file5') < io('file4'); '>>' and '<<' do the same thing except the recipient string or file is appended to. An IO::All file used as an array reference becomes tied using Tie::File: $file = io "file"; # Print last line of file print $file->[-1]; # Insert new line in middle of file $file->[$#$file / 2] = 'New line'; An IO::All file used as a hash reference becomes tied to a DBM class: io('mydbm')->{ingy} = 'YAML'; An IO::All directory used as an array reference, will expose each file or subdirectory as an element of the array. print "$_\n" for @{io 'dir'}; IO::All directories used as hash references have file names as keys, and IO::All objects as values: print io('dir')->{'foo.txt'}->slurp; Files used as scalar references get slurped: print ${io('dir')->{'foo.txt'}}; Not all combinations of operations and object types are supported. Some just haven't been added yet, and some just don't make sense. If you use an invalid combination, an error will be thrown. =head1 COOKBOOK This section describes some various things that you can easily cook up with IO::All. =head2 File Locking IO::All makes it very easy to lock files. Just use the C method. Here's a standalone program that demonstrates locking for both write and read: use IO::All; my $io1 = io('myfile')->lock; $io1->println('line 1'); fork or do { my $io2 = io('myfile')->lock; print $io2->slurp; exit; }; sleep 1; $io1->println('line 2'); $io1->println('line 3'); $io1->unlock; There are a lot of subtle things going on here. An exclusive lock is issued for C<$io1> on the first C. That's because the file isn't actually opened until the first IO operation. When the child process tries to read the file using C<$io2>, there is a shared lock put on it. Since C<$io1> has the exclusive lock, the slurp blocks. The parent process sleeps just to make sure the child process gets a chance. The parent needs to call C or C to release the lock. If all goes well the child will print 3 lines. =head2 Round Robin This simple example will read lines from a file forever. When the last line is read, it will reopen the file and read the first one again. my $io = io 'file1.txt'; $io->autoclose(1); while (my $line = $io->getline || $io->getline) { print $line; } =head2 Reading Backwards If you call the C method on an IO::All object, the C and C will work in reverse. They will read the lines in the file from the end to the beginning. my @reversed; my $io = io('file1.txt'); $io->backwards; while (my $line = $io->getline) { push @reversed, $line; } or more simply: my @reversed = io('file1.txt')->backwards->getlines; The C method returns the IO::All object so that you can chain the calls. NOTE: This operation requires that you have the L module installed. =head2 Client/Server Sockets IO::All makes it really easy to write a forking socket server and a client to talk to it. In this example, a server will return 3 lines of text, to every client that calls it. Here is the server code: use IO::All; my $socket = io(':12345')->fork->accept; $socket->print($_) while ; $socket->close; __DATA__ On your mark, Get set, Go! Here is the client code: use IO::All; my $io = io('localhost:12345'); print while $_ = $io->getline; You can run the server once, and then run the client repeatedly (in another terminal window). It should print the 3 data lines each time. Note that it is important to close the socket if the server is forking, or else the socket won't go out of scope and close. =head2 A Tiny Web Server Here is how you could write a simplistic web server that works with static and dynamic pages: perl -MIO::All -e 'io(":8080")->fork->accept->(sub { $_[0] < io(-x $1 ? "./$1 |" : $1) if /^GET \/(.*) / })' There is are a lot of subtle things going on here. First we accept a socket and fork the server. Then we overload the new socket as a code ref. This code ref takes one argument, another code ref, which is used as a callback. The callback is called once for every line read on the socket. The line is put into C<$_> and the socket itself is passed in to the callback. Our callback is scanning the line in C<$_> for an HTTP GET request. If one is found it parses the file name into C<$1>. Then we use C<$1> to create an new IO::All file object... with a twist. If the file is executable (C<-x>), then we create a piped command as our IO::All object. This somewhat approximates CGI support. Whatever the resulting object is, we direct the contents back at our socket which is in C<$_[0]>. Pretty simple, eh? =head2 DBM Files IO::All file objects used as a hash reference, treat the file as a DBM tied to a hash. Here I write my DB record to STDERR: io("names.db")->{ingy} > io('='); Since their are several DBM formats available in Perl, IO::All picks the first one of these that is installed on your system: DB_File GDBM_File NDBM_File ODBM_File SDBM_File You can override which DBM you want for each IO::All object: my @keys = keys %{io('mydbm')->dbm('SDBM_File')}; =head2 File Subclassing Subclassing is easy with IO::All. Just create a new module and use IO::All as the base class, like this: package NewModule; use IO::All -base; You need to do it this way so that IO::All will export the C function. Here is a simple recipe for subclassing: IO::Dumper inherits everything from IO::All and adds an extra method called C, which will dump a data structure to the file we specify in the C function. Since it needs Data::Dumper to do the dumping, we override the C method to C and then pass control to the real C. First the code using the module: use IO::Dumper; io('./mydump')->dump($hash); And next the IO::Dumper module itself: package IO::Dumper; use IO::All -base; use Data::Dumper; sub dump { my $self = shift; Dumper(@_) > $self; } 1; =head2 Inline Subclassing This recipe does the same thing as the previous one, but without needing to write a separate module. The only real difference is the first line. Since you don't "use" IO::Dumper, you need to still call its C method manually. IO::Dumper->import; io('./mydump')->dump($hash); package IO::Dumper; use IO::All -base; use Data::Dumper; sub dump { my $self = shift; Dumper(@_) > $self; } =head1 THE IO::All METHODS This section gives a full description of all of the methods that you can call on IO::All objects. The methods have been grouped into subsections based on object construction, option settings, configuration, action methods and support for specific modules. =head2 Object Construction and Initialization Methods =over 4 =item * new There are three ways to create a new IO::All object. The first is with the special function C which really just calls C<< IO::All->new >>. The second is by calling C as a class method. The third is calling C as an object instance method. In this final case, the new objects attributes are copied from the instance object. io(file-descriptor); IO::All->new(file-descriptor); $io->new(file-descriptor); All three forms take a single argument, a file descriptor. A file descriptor can be any of the following: - A file name - A file handle - A directory name - A directory handle - A typeglob reference - A piped shell command. eq '| ls -al' - A socket domain/port. eg 'perl.com:5678' - '-' means STDIN or STDOUT (depending on usage) - '=' means STDERR - '$' means an IO::String object - '?' means a temporary file - A URI including: http, https, ftp and mailto - An IO::All object If you provide an IO::All object, you will simply get that I returned from the constructor. If no file descriptor is provided, an object will still be created, but it must be defined by one of the following methods before it can be used for I/O: =item * file io->file("path/to/my/file.txt"); Using the C method sets the type of the object to I and sets the pathname of the file if provided. It might be important to use this method if you had a file whose name was C<'-'>, or if the name might otherwise be confused with a directory or a socket. In this case, either of these statements would work the same: my $file = io('-')->file; my $file = io->file('-'); =item * dir io->dir($dir_name); Make the object be of type I. =item * socket io->socket("${domain}:${port}"); Make the object be of type I. =item * link io->link($link_name); Make the object be of type I. =item * pipe io->pipe($pipe_command); Make the object be of type I. The following two statements are equivalent: my $io = io('ls -l |'); my $io = io('ls -l')->pipe; my $io = io->pipe('ls -l'); =item * dbm This method takes the names of zero or more DBM modules. The first one that is available is used to process the dbm file. io('mydbm')->dbm('NDBM_File', 'SDBM_File')->{author} = 'ingy'; If no module names are provided, the first available of the following is used: DB_File GDBM_File NDBM_File ODBM_File SDBM_File =item * mldbm Similar to the C method, except create a Multi Level DBM object using the MLDBM module. This method takes the names of zero or more DBM modules and an optional serialization module. The first DBM module that is available is used to process the MLDBM file. The serialization module can be Data::Dumper, Storable or FreezeThaw. io('mymldbm')->mldbm('GDBM_File', 'Storable')->{author} = {nickname => 'ingy'}; =item * string Make the object be an IO::String object. These are equivalent: my $io = io('$'); my $io = io->string; =item * temp Make the object represent a temporary file. It will automatically be open for both read and write. =item * stdio Make the object represent either STDIN or STDOUT depending on how it is used subsequently. These are equivalent: my $io = io('-'); my $io = io->stdin; =item * stdin Make the object represent STDIN. =item * stdout Make the object represent STDOUT. =item * stderr Make the object represent STDERR. =item * handle io->handle($io_handle); Forces the object to be created from an pre-existing IO handle. You can chain calls together to indicate the type of handle: my $file_object = io->file->handle($file_handle); my $dir_object = io->dir->handle($dir_handle); =item * http Make the object represent an HTTP URI. Requires IO-All-LWP. =item * https Make the object represent an HTTPS URI. Requires IO-All-LWP. =item * ftp Make the object represent an FTP URI. Requires IO-All-LWP. =item * mailto Make the object represent a C URI. Requires IO-All-Mailto. =back If you need to use the same options to create a lot of objects, and don't want to duplicate the code, just create a dummy object with the options you want, and use that object to spawn other objects. my $lt = io->lock->tie; ... my $io1 = $lt->new('file1'); my $io2 = $lt->new('file2'); Since the new method copies attributes from the calling object, both C<$io1> and C<$io2> will be locked and tied. =head2 Option Setting Methods The following methods don't do any actual I/O, but they specify options about how the I/O should be done. Each option can take a single argument of 0 or 1. If no argument is given, the value 1 is assumed. Passing 0 turns the option off. All of these options return the object reference that was used to invoke them. This is so that the option methods can be chained together. For example: my $io = io('path/file')->tie->assert->chomp->lock; =over 4 =item * absolute Indicates that the C for the object should be made absolute. # Print the full path of the current working directory # (like pwd). use IO::All; print io->curdir->absolute; =item * assert This method ensures that the path for a file or directory actually exists before the file is open. If the path does not exist, it is created. For example, here is a program called "create-cat-to" that outputs to a file that it creates. #!/usr/bin/perl # create-cat-to.pl # cat to a file that can be created. use strict; use warnings; use IO::All; my $filename = shift(@ARGV); # Create a file called $filename, including all leading components. io('-') > io->file($filename)->assert; Here's an example use of it: $ ls -l total 0 $ echo "Hello World" | create-cat-to one/two/three/four.txt $ ls -l total 4 drwxr-xr-x 3 shlomif shlomif 4096 2010-10-14 18:03 one/ $ cat one/two/three/four.txt Hello World $ =item * autoclose By default, IO::All will close an object opened for input when EOF is reached. By closing the handle early, one can immediately do other operations on the object without first having to close it. This option is on by default, so if you don't want this behaviour, say so like this: $io->autoclose(0); The object will then be closed when C<$io> goes out of scope, or you manually call C<< $io->close >>. =item * autoflush Proxy for IO::Handle::autoflush =item * backwards Sets the object to 'backwards' mode. All subsequent C operations will read backwards from the end of the file. Requires the File::ReadBackwards CPAN module. =item * binary Indicates the file has binary content and should be opened with C. =item * chdir chdir() to the pathname of a directory object. When object goes out of scope, chdir back to starting directory. =item * chomp Indicates that all operations that read lines should chomp the lines. If the C method has been called, chomp will remove that value from the end of each record. =item * confess Errors should be reported with the very detailed Carp::confess function. =item * deep Indicates that calls to the C family of methods should search directories as deep as possible. =item * fork Indicates that the process should automatically be forked inside the C socket method. =item * lock Indicate that operations on an object should be locked using flock. =item * rdonly This option indicates that certain operations like DBM and Tie::File access should be done in read-only mode. =item * rdwr This option indicates that DBM and MLDBM files should be opened in read- write mode. =item * relative Indicates that the C for the object should be made relative. =item * sort Indicates whether objects returned from one of the C methods will be in sorted order by name. True by default. =item * tie Indicate that the object should be tied to itself, thus allowing it to be used as a filehandle in any of Perl's builtin IO operations. my $io = io('foo')->tie; @lines = <$io>; =item * utf8 Indicates that IO should be done using utf8 encoding. Calls binmode with C<:utf8> layer. =back =head2 Configuration Methods The following methods don't do any actual I/O, but they set specific values to configure the IO::All object. If these methods are passed no argument, they will return their current value. If arguments are passed they will be used to set the current value, and the object reference will be returned for potential method chaining. =over 4 =item * bcc Set the Bcc field for a mailto object. =item * binmode Proxy for binmode. Requires a layer to be passed. Use C for plain binary mode. =item * block_size The default length to be used for C and C calls. Defaults to 1024. =item * buffer Returns a reference to the internal buffer, which is a scalar. You can use this method to set the buffer to a scalar of your choice. (You can just pass in the scalar, rather than a reference to it.) This is the buffer that C and C will use by default. You can easily have IO::All objects use the same buffer: my $input = io('abc'); my $output = io('xyz'); my $buffer; $output->buffer($input->buffer($buffer)); $output->write while $input->read; =item * cc Set the Cc field for a mailto object. =item * content Get or set the content for an LWP operation manually. =item * domain Set the domain name or ip address that a socket should use. =item * encoding Set the encoding to be used for the PerlIO layer. =item * errors Use this to set a subroutine reference that gets called when an internal error is thrown. =item * filter Use this to set a subroutine reference that will be used to grep which objects get returned on a call to one of the C methods. For example: my @odd = io->curdir->filter(sub {$_->size % 2})->All_Files; C<@odd> will contain all the files under the current directory whose size is an odd number of bytes. =item * from Indicate the sender for a mailto object. =item * mailer Set the mailer program for a mailto transaction. Defaults to 'sendmail'. =item * mode Set the mode for which the file should be opened. Examples: $io->mode('>>')->open; $io->mode(O_RDONLY); my $log_appender = io->file('/var/log/my-application.log') ->mode('>>')->open(); $log_appender->print("Stardate 5987.6: Mission accomplished."); =item * name Set or get the name of the file or directory represented by the IO::All object. =item * password Set the password for an LWP transaction. =item * perms Sets the permissions to be used if the file/directory needs to be created. =item * port Set the port number that a socket should use. =item * request Manually specify the request object for an LWP transaction. =item * response Returns the resulting response object from an LWP transaction. =item * separator Sets the record (line) separator to whatever value you pass it. Default is \n. Affects the chomp setting too. =item * string_ref Proxy for IO::String::string_ref Returns a reference to the internal string that is acting like a file. =item * subject Set the subject for a mailto transaction. =item * to Set the recipient address for a mailto request. =item * uri Direct access to the URI used in LWP transactions. =item * user Set the user name for an LWP transaction. =back =head2 IO Action Methods These are the methods that actually perform I/O operations on an IO::All object. The stat methods and the File::Spec methods are documented in separate sections below. =over 4 =item * accept For sockets. Opens a server socket (LISTEN => 1, REUSE => 1). Returns an IO::All socket object that you are listening on. If the C method was called on the object, the process will automatically be forked for every connection. =item * all Read all contents into a single string. compare(io('file1')->all, io('file2')->all); =item * all (For directories) Returns a list of IO::All objects for all files and subdirectories in a directory. '.' and '..' are excluded. Takes an optional argument telling how many directories deep to search. The default is 1. Zero (0) means search as deep as possible. The filter method can be used to limit the results. The items returned are sorted by name unless C<< ->sort(0) >> is used. =item * All Same as C. =item * all_dirs Same as C, but only return directories. =item * All_Dirs Same as C. =item * all_files Same as C, but only return files. =item * All_Files Same as C. =item * all_links Same as C, but only return links. =item * All_Links Same as C. =item * append Same as print, but sets the file mode to '>>'. =item * appendf Same as printf, but sets the file mode to '>>'. =item * appendln Same as println, but sets the file mode to '>>'. =item * clear Clear the internal buffer. This method is called by C after it writes the buffer. Returns the object reference for chaining. =item * close Close will basically unopen the object, which has different meanings for different objects. For files and directories it will close and release the handle. For sockets it calls shutdown. For tied things it unties them, and it unlocks locked things. =item * empty Returns true if a file exists but has no size, or if a directory exists but has no contents. =item * eof Proxy for IO::Handle::eof =item * ext Returns the extension of the file. Can also be spelled as C =item * exists Returns whether or not the file or directory exists. =item * filename Return the name portion of the file path in the object. For example: io('my/path/file.txt')->filename; would return C. =item * fileno Proxy for IO::Handle::fileno =item * filepath Return the path portion of the file path in the object. For example: io('my/path/file.txt')->filepath; would return C. =item * get Perform an LWP GET request manually. =item * getc Proxy for IO::Handle::getc =item * getline Calls IO::File::getline. You can pass in an optional record separator. =item * getlines Calls IO::File::getlines. You can pass in an optional record separator. =item * glob Creates IO::All objects for the files matching the glob in the IO::All::Dir. For example: io->dir($ENV{HOME})->glob('*.txt') =item * head Return the first 10 lines of a file. Takes an optional argument which is the number of lines to return. Works as expected in list and scalar context. Is subject to the current line separator. =item * io_handle Direct access to the actual IO::Handle object being used on an opened IO::All object. =item * is_dir Returns boolean telling whether or not the IO::All object represents a directory. =item * is_executable Returns true if file or directory is executable. =item * is_dbm Returns boolean telling whether or not the IO::All object represents a dbm file. =item * is_file Returns boolean telling whether or not the IO::All object represents a file. =item * is_link Returns boolean telling whether or not the IO::All object represents a symlink. =item * is_mldbm Returns boolean telling whether or not the IO::All object represents a mldbm file. =item * is_open Indicates whether the IO::All is currently open for input/output. =item * is_pipe Returns boolean telling whether or not the IO::All object represents a pipe operation. =item * is_readable Returns true if file or directory is readable. =item * is_socket Returns boolean telling whether or not the IO::All object represents a socket. =item * is_stdio Returns boolean telling whether or not the IO::All object represents a STDIO file handle. =item * is_string Returns boolean telling whether or not the IO::All object represents an IO::String object. =item * is_temp Returns boolean telling whether or not the IO::All object represents a temporary file. =item * is_writable Returns true if file or directory is writable. Can also be spelled as C. =item * length Return the length of the internal buffer. =item * mimetype Return the mimetype of the file. Requires a working installation of the L CPAN module. =item * mkdir Create the directory represented by the object. =item * mkpath Create the directory represented by the object, when the path contains more than one directory that doesn't exist. Proxy for File::Path::mkpath. =item * next For a directory, this will return a new IO::All object for each file or subdirectory in the directory. Return undef on EOD. =item * open Open the IO::All object. Takes two optional arguments C and C, which can also be set ahead of time using the C and C methods. NOTE: Normally you won't need to call open (or mode/perms), since this happens automatically for most operations. =item * os Change the object's os representation. Valid options are: C, C, C, C, C. =item * pathname Return the absolute or relative pathname for a file or directory, depending on whether object is in C or C mode. =item * print Proxy for IO::Handle::print =item * printf Proxy for IO::Handle::printf =item * println Same as print, but adds newline to each argument unless it already ends with one. =item * put Perform an LWP PUT request manually. =item * read This method varies depending on its context. Read carefully (no pun intended). For a file, this will proxy IO::File::read. This means you must pass it a buffer, a length to read, and optionally a buffer offset for where to put the data that is read. The function returns the length actually read (which is zero at EOF). If you don't pass any arguments for a file, IO::All will use its own internal buffer, a default length, and the offset will always point at the end of the buffer. The buffer can be accessed with the C method. The length can be set with the C method. The default length is 1024 bytes. The C method can be called to clear the buffer. For a directory, this will proxy IO::Dir::read. =item * readdir Similar to the Perl C builtin. In scalar context, return the next directory entry (ie file or directory name), or undef on end of directory. In list context, return all directory entries. Note that C does not return the special C<.> and C<..> entries. =item * readline Same as C. =item * readlink Calls Perl's readlink function on the link represented by the object. Instead of returning the file path, it returns a new IO::All object using the file path. =item * recv Proxy for IO::Socket::recv =item * rename my $new = $io->rename('new-name'); Calls Perl's rename function and returns an IO::All object for the renamed file. Returns false if the rename failed. =item * rewind Proxy for IO::Dir::rewind =item * rmdir Delete the directory represented by the IO::All object. =item * rmtree Delete the directory represented by the IO::All object and all the files and directories beneath it. Proxy for File::Path::rmtree. =item * scalar Deprecated. Same as C. =item * seek Proxy for IO::Handle::seek. If you use seek on an unopened file, it will be opened for both read and write. =item * send Proxy for IO::Socket::send =item * shutdown Proxy for IO::Socket::shutdown =item * slurp Read all file content in one operation. Returns the file content as a string. In list context returns every line in the file. =item * stat Proxy for IO::Handle::stat =item * sysread Proxy for IO::Handle::sysread =item * syswrite Proxy for IO::Handle::syswrite =item * tail Return the last 10 lines of a file. Takes an optional argument which is the number of lines to return. Works as expected in list and scalar context. Is subject to the current line separator. =item * tell Proxy for IO::Handle::tell =item * throw This is an internal method that gets called whenever there is an error. It could be useful to override it in a subclass, to provide more control in error handling. =item * touch Update the atime and mtime values for a file or directory. Creates an empty file if the file does not exist. =item * truncate Proxy for IO::Handle::truncate =item * type Returns a string indicated the type of io object. Possible values are: file dir link socket string pipe Returns undef if type is not determinable. =item * unlink Unlink (delete) the file represented by the IO::All object. NOTE: You can unlink a file after it is open, and continue using it until it is closed. =item * unlock Release a lock from an object that used the C method. =item * utime Proxy for the utime Perl function. =item * write Opposite of C for file operations only. NOTE: When used with the automatic internal buffer, C will clear the buffer after writing it. =back =head2 Stat Methods This methods get individual values from a stat call on the file, directory or handle represented by the IO::All object. =over 4 =item * atime Last access time in seconds since the epoch =item * blksize Preferred block size for file system I/O =item * blocks Actual number of blocks allocated =item * ctime Inode change time in seconds since the epoch =item * device Device number of filesystem =item * device_id Device identifier for special files only =item * gid Numeric group id of file's owner =item * inode Inode number =item * modes File mode - type and permissions =item * mtime Last modify time in seconds since the epoch =item * nlink Number of hard links to the file =item * size Total size of file in bytes =item * uid Numeric user id of file's owner =back =head2 File::Spec Methods These methods are all adaptations from File::Spec. Each method actually does call the matching File::Spec method, but the arguments and return values differ slightly. Instead of being file and directory B, they are IO::All B. Since IO::All objects stringify to their names, you can generally use the methods just like File::Spec. =over 4 =item * abs2rel Returns the relative path for the absolute path in the IO::All object. Can take an optional argument indicating the base path. =item * canonpath Returns the canonical path for the IO::All object. =item * case_tolerant Returns 0 or 1 indicating whether the file system is case tolerant. Since an active IO::All object is not needed for this function, you can code it like: IO::All->case_tolerant; or more simply: io->case_tolerant; =item * catdir Concatenate the directory components together, and return a new IO::All object representing the resulting directory. =item * catfile Concatenate the directory and file components together, and return a new IO::All object representing the resulting file. my $contents = io->catfile(qw(dir subdir file))->slurp; This is a very portable way to read C. =item * catpath Concatenate the volume, directory and file components together, and return a new IO::All object representing the resulting file. =item * curdir Returns an IO::All object representing the current directory. =item * devnull Returns an IO::All object representing the /dev/null file. =item * is_absolute Returns 0 or 1 indicating whether the C field of the IO::All object is an absolute path. =item * join Same as C. =item * path Returns a list of IO::All directory objects for each directory in your path. =item * rel2abs Returns the absolute path for the relative path in the IO::All object. Can take an optional argument indicating the base path. =item * rootdir Returns an IO::All object representing the root directory on your file system. =item * splitdir Returns a list of the directory components of a path in an IO::All object. =item * splitpath Returns a volume directory and file component of a path in an IO::All object. =item * tmpdir Returns an IO::All object representing a temporary directory on your file system. =item * updir Returns an IO::All object representing the current parent directory. =back =head1 OPERATIONAL NOTES =over 4 =item * Each IO::All object gets reblessed into an IO::All::* object as soon as IO::All can determine what type of object it should be. Sometimes it gets reblessed more than once: my $io = io('mydbm.db'); $io->dbm('DB_File'); $io->{foo} = 'bar'; In the first statement, $io has a reference value of 'IO::All::File', if C exists. In the second statement, the object is reblessed into class 'IO::All::DBM'. =item * An IO::All object will automatically be opened as soon as there is enough contextual information to know what type of object it is, and what mode it should be opened for. This is usually when the first read or write operation is invoked but might be sooner. =item * The mode for an object to be opened with is determined heuristically unless specified explicitly. =item * For input, IO::All objects will automatically be closed after EOF (or EOD). For output, the object closes when it goes out of scope. To keep input objects from closing at EOF, do this: $io->autoclose(0); =item * You can always call C and C explicitly, if you need that level of control. To test if an object is currently open, use the C method. =item * Overloaded operations return the target object, if one exists. This would set C<$xxx> to the IO::All object: my $xxx = $contents > io('file.txt'); While this would set C<$xxx> to the content string: my $xxx = $contents < io('file.txt'); =back =head1 STABILITY The goal of the IO::All project is to continually refine the module to be as simple and consistent to use as possible. Therefore, in the early stages of the project, I will not hesitate to break backwards compatibility with other versions of IO::All if I can find an easier and clearer way to do a particular thing. IO is tricky stuff. There is definitely more work to be done. On the other hand, this module relies heavily on very stable existing IO modules; so it may work fairly well. I am sure you will find many unexpected "features". Please send all problems, ideas and suggestions to ingy@cpan.org. =head2 Known Bugs and Deficiencies Not all possible combinations of objects and methods have been tested. There are many many combinations. All of the examples have been tested. If you find a bug with a particular combination of calls, let me know. If you call a method that does not make sense for a particular object, the result probably won't make sense. Little attempt is made to check for improper usage. =head1 SEE ALSO IO::Handle, IO::File, IO::Dir, IO::Socket, IO::String, File::Spec, File::Path, File::ReadBackwards, Tie::File, File::MimeInfo =head1 CREDITS A lot of people have sent in suggestions, that have become a part of IO::All. Thank you. Special thanks to Ian Langworth for continued testing and patching. Thank you Simon Cozens for tipping me off to the overloading possibilities. Finally, thanks to Autrijus Tang, for always having one more good idea. (It seems IO::All of it to a lot of people!) =head1 REPOSITORY AND COMMUNITY The IO::All module can be found on CPAN and on GitHub: L. Please join the IO::All discussion on #io-all on irc.perl.org. =head1 AUTHOR Ingy döt Net =head1 COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008, 2010. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L =cut IO_Dumper.pm100644001750001750 53212267312543 14242 0ustar00frewfrew000000000000IO-All-0.54/tpackage IO_Dumper; use strict; use warnings; use IO::All -base; our @EXPORT = 'io'; sub io { return IO_Dumper->new(@_) }; package IO::All::Filesys; use Data::Dumper; sub dump { my $self = shift; local $Data::Dumper::Indent = 1; local $Data::Dumper::Sortkeys = 1; $self->print(Data::Dumper::Dumper(@_)); return $self; } 1; read_write.t100644001750001750 42112267312543 14370 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 2; use IO::All; use IO_All_Test; my $io = io('lib/IO/All.pm'); my $buffer; $io->buffer($buffer); 1 while $io->read; ok(length($buffer)); test_file_contents($buffer, 'lib/IO/All.pm'); del_output_dir(); subtleties.t100644001750001750 74412267312543 14436 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 7; use IO::All; use IO_All_Test; my $data = join '', ; my $io = io(o_dir() . '/subtleties1') < $data; is("$io", o_dir() . '/subtleties1'); ok($io->close); ok(not $io->close); my $data2 = $io->slurp; $data2 .= $$io; $data2 << $io; is($data2, $data x 3); ok(not $io->close); my $io2 = io(io(io('xxx'))); ok(ref $io2); ok($io2->isa('IO::All')); # is("$io2", 'xxx'); del_output_dir(); __DATA__ test data client.pl100644001750001750 13412267312543 14406 0ustar00frewfrew000000000000IO-All-0.54/unituse lib 'lib'; use IO::All; my $io = io('localhost:12345'); print while $_ = $io->getline; append.pl100644001750001750 23312267312543 14377 0ustar00frewfrew000000000000IO-All-0.54/unituse lib 'lib'; use IO::All; my $io = io('foo'); $io->append(io($0)->slurp); my @stuff = qw(one two three); $stuff[1] .= "xxx\n"; $io->appendln(@stuff); server.pl100644001750001750 23712267312543 14442 0ustar00frewfrew000000000000IO-All-0.54/unituse lib 'lib'; use IO::All; my $socket = io(':12345')->accept('-fork'); $socket->print($_) while ; $socket->close; __DATA__ On your mark, Get set, Go! round_robin.t100644001750001750 61612267312543 14571 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 9; use IO::All; my $io = io('t/mystuff'); my $x = 0; while (my $line = $io->getline || $io->getline) { my $expected = ; is($line, $expected); last if ++$x >= 8; } is(, "last line\n"); __DATA__ My stuff is quite enough. No bluff. My stuff is quite enough. No bluff. My stuff is quite enough. last line string_open.t100644001750001750 54112267312543 14575 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 1; use IO::All; use IO_All_Test; my $s = io('$'); $s->append("write 1\n"); my $s1 = "IO::String ref: (".$s->string_ref.")"; $s->append("write 2\n"); my $s2 = "IO::String ref: (".$s->string_ref.")"; is($s1, $s2, "Don't create new string object with each write"); del_output_dir(); println.pl100644001750001750 15612267312543 14622 0ustar00frewfrew000000000000IO-All-0.54/unituse lib 'lib'; use IO::All; my @stuff = qw(one two three); $stuff[1] .= "xxx\n"; io('-')->println(@stuff); Notes000755001750001750 012267312543 12566 5ustar00frewfrew000000000000IO-All-0.54Design.st100644001750001750 116712267312543 14514 0ustar00frewfrew000000000000IO-All-0.54/Notes^ Introduction Perl provides all the foundational functionality for Input/Output in all its myriad forms. Unforatunately using all these primitives is unnecessarily tedious. IO::All was introduced in 2005 as a proof of concept that IO operations could all be pleasantly simple and consistent. While IO::All is off to a good start, it is not completely polished. It is time for a rewrite. It makes sense to have a solid plan/specification, before writing the code. This document is intended to be just that. ^ Current Design Concepts * Export one function, `io`, that acts constructs an IO::All object. ^ Current Deficiencies Design.md100644001750001750 755212267312543 14472 0ustar00frewfrew000000000000IO-All-0.54/Notes# Introduction This is a design document for an upcoming version of IO::All. IO::All is a Perl module that attempts to make all Input/Output operations in Perl, as simple and normal as possible. IO::All has been in existence since 2005. It is useful and somewhat extensible, but has a number of inconsistencies, flaws and misgivings. This document will propose a better way to do it, and will also discuss how to move the current API forward to the new API. # Basic Principles of how IO::All should work * IO::All provides a single entry point function called `io`. * `use IO::All` should make this function available in a lexical scope. * Currently this scope is 'package' scope. * Would be nice, but maybe not possible to have true lexical scope. * The `io` function is custom to its scope * The behavior it provides depends on the state of the scope * The behavior it provides also depends on the arguments passed to `use IO::All` * `io` returns an IO::All object * The IO::All object has no I/O capabilities * Further method calls invoke a context, causing the IO::All object to rebless itself it something useful like IO::All::File. * Certain methods force a rebless * `file(...), dir(...), socket(...), etc * These methods are more or less hard-coded currently * Options to `use IO::All` that begin with a `-`, cause a method to be called on each new IO::All object. * use IO::All -encoding => 'big5'; # causes: * io('foo')->print('hi'); # to mean: * io('foo')->encoding('big5')->print('hi'); * IO::All operations generally return other IO::All objects * Often they return themselves ($self) for chaining * IO::All needs to be completely and consistently extensible * The extensions that ship with IO-All should be the same as third party extensions * Extensions register capabilities with IO::All (tied to a scope) * IO::All operations can be strict or loose. Strict always throws errors on any possible error condition. Strict or loose should be determined by the presence of `use strict` in the scope (possibly). * IO::All currently uses a big set of overloaded operations by default. This is loved by some and hated by others. It should probably be off by default for 2.0. # IO::All Extensions Currently the extension API is fairly muddy. I would like the new API to require something like this: { use strict; use IO::All -overload; use IO::All::PrintingPress; my $io = io('path:to:printing:press#1'); # is ref($io), 'IO::All'; $io->print('IO::All'); # calls IO::All::PrintingPress::print # is ref($io), 'IO::All::PrintingPress'; } So you need to load any extensions that you want to use, within the scope that you want them in. Exceptions are IO::All::File and IO::All::Dir, which are automatically loaded, unless you say: use IO::All -none; Extensions can register 2 things: 1. Register a method (or methods) that will force a rebless in that class. 2. Register a regexp (or function) that will cause a rebless when the input to io(...) matches. These things are register according to the scope of the IO::All, so that the `io` function will do the right things. # Transition to the new API It needs to be determined if the changes that need to be made are too destructive to coexist with the current IO::All. That determination obviously cannot be made until the new design is complete. If it is not too destructive, IO::All and its extensions can be brought forward. If it is too destructive, here is one proposed solution: Support IO::All 2 ; The version '2' will load IO::All2 (or something) and no version will load the old code. It is important to assure that the old and new interfaces can coexist in the same process space. In the IO::All2 scenario, we would need to figure out if the current IO::All extensions also needed forwarding. IO_All_Test.pm100644001750001750 310312267312543 14532 0ustar00frewfrew000000000000IO-All-0.54/tpackage IO_All_Test; use File::Path; @EXPORT = qw( del_output_dir o_dir test_file_contents test_file_contents2 test_matching_files read_file_lines flip_slash f $output_dir ); use strict; use base 'Exporter'; use Test::More (); sub test_file_contents { my ($data, $file) = @_; Test::More::is($data, read_file($file)); } sub test_file_contents2 { my ($file, $data) = @_; Test::More::is(read_file($file), $data); } sub test_matching_files { my ($file1, $file2) = @_; Test::More::is(read_file($file1), read_file($file2)); } sub read_file { my ($file) = @_; local(*FILE, $/); open FILE, $file or die "Can't open $file for input:\n$!"; return scalar ; } sub read_file_lines { my ($file) = @_; local(*FILE); open FILE, $file or die $!; (); } sub flip_slash { my $string = shift; if ($^O =~ /^mswin32$/i) { $string =~ s/\//\\/g; } return $string; } { no warnings; *f = \&flip_slash; } use vars qw($output_dir); BEGIN { use FindBin qw($Script); use File::Temp qw(tempdir); if ($Script =~ m{([\w\-]+)\.t\z}) { $output_dir = "t/output__$1"; } else { $output_dir = tempdir('t/output__XXXXXXXX'); } } sub o_dir { return $output_dir; } sub del_output_dir { File::Path::rmtree($output_dir); } # TODO : this common directory that is deleted and recreated may prevent # running the tests in parallel. BEGIN { if (-d $output_dir) { del_output_dir(); } File::Path::mkpath($output_dir); } 1; import_flags.t100644001750001750 306312267312543 14756 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More; use IO_All_Test; BEGIN { plan(($] < 5.008003) ? (skip_all => 'Broken on older perls') : (tests => 16) ); } package One; use IO::All -strict; package Two; use IO::All -utf8; package Three; use IO::All -strict, -utf8; package Four; use IO::All -foo; package main; main::ok(defined &One::io, 'io is exported to One'); main::ok(defined &Two::io, 'io is exported to Two'); main::ok(defined &Three::io, 'io is exported to Three'); main::ok(defined &Four::io, 'io is exported to Four'); my $io1 = One::io('xxx'); ok $io1->_strict, 'strict flag set on object 1'; ok not($io1->_utf8), 'utf8 flag not set on object 1'; my $io2 = Two::io('xxx'); ok not($io2->_strict), 'strict flag not set on object 2'; ok $io2->_utf8, 'utf8 flag set on object 2'; my $io3 = Three::io('xxx'); ok $io3->_strict, 'strict flag set on object 3'; ok $io3->_utf8, 'utf8 flag set on object 3'; eval "Four::io('xxx')"; like $@, qr/Can't find a class for method 'foo'/, '-foo flag causes error'; my $io2b = $io2->catfile('yyy'); is $io2b->name, f('xxx/yyy'), 'catfile name is correct'; ok not($io2b->_strict), 'strict flag not set on object 2b (propagated from 2)'; ok $io2b->_utf8, 'utf8 flag set on object 2b (propagated from 2)'; my $io2c = Two::io('aaa')->curdir; # use Data::Dumper; # die Dumper \%{*$io2c}; ok not($io2c->_strict), 'strict flag not set on object 2c (propagated from 2)'; ok $io2c->_utf8, 'utf8 flag set on object 2c (propagated from 2)'; del_output_dir(); All000755001750001750 012267312543 13263 5ustar00frewfrew000000000000IO-All-0.54/lib/IODBM.pm100644001750001750 575112267312543 14373 0ustar00frewfrew000000000000IO-All-0.54/lib/IO/Allpackage IO::All::DBM; use strict; use warnings; use IO::All::File -base; use Fcntl; field _dbm_list => []; field '_dbm_class'; field _dbm_extra => []; sub dbm { my $self = shift; bless $self, __PACKAGE__; $self->_dbm_list([@_]); return $self; } sub assert_open { my $self = shift; return $self->tied_file if $self->tied_file; $self->open; } sub assert_filepath { my $self = shift; $self->SUPER::assert_filepath(@_); if ($self->_rdonly and not -e $self->pathname) { my $rdwr = $self->_rdwr; $self->assert(0)->rdwr(1)->rdonly(0)->open; $self->close; $self->assert(1)->rdwr($rdwr)->rdonly(1); } } sub open { my $self = shift; $self->is_open(1); return $self->tied_file if $self->tied_file; $self->assert_filepath if $self->_assert; my $dbm_list = $self->_dbm_list; my @dbm_list = @$dbm_list ? @$dbm_list : (qw(DB_File GDBM_File NDBM_File ODBM_File SDBM_File)); my $dbm_class; for my $module (@dbm_list) { (my $file = "$module.pm") =~ s{::}{/}g; if (defined $INC{$file} || eval "eval 'use $module; 1'") { $self->_dbm_class($module); last; } } $self->throw("No module available for IO::All DBM operation") unless defined $self->_dbm_class; my $mode = $self->_rdonly ? O_RDONLY : O_RDWR; if ($self->_dbm_class eq 'DB_File::Lock') { $self->_dbm_class->import; my $type = eval '$DB_HASH'; die $@ if $@; # XXX Not sure about this warning warn "Using DB_File::Lock in IO::All without the rdonly or rdwr method\n" if not ($self->_rdwr or $self->_rdonly); my $flag = $self->_rdwr ? 'write' : 'read'; $mode = $self->_rdwr ? O_RDWR : O_RDONLY; $self->_dbm_extra([$type, $flag]); } $mode |= O_CREAT if $mode & O_RDWR; $self->mode($mode); $self->perms(0666) unless defined $self->perms; return $self->tie_dbm; } sub tie_dbm { my $self = shift; my $hash; my $filename = $self->name; my $db = tie %$hash, $self->_dbm_class, $filename, $self->mode, $self->perms, @{$self->_dbm_extra} or $self->throw("Can't open '$filename' as DBM file:\n$!"); $self->add_utf8_dbm_filter($db) if $self->_utf8; $self->tied_file($hash); } sub add_utf8_dbm_filter { my $self = shift; my $db = shift; $db->filter_store_key(sub { utf8::encode($_) }); $db->filter_store_value(sub { utf8::encode($_) }); $db->filter_fetch_key(sub { utf8::decode($_) }); $db->filter_fetch_value(sub { utf8::decode($_) }); } =encoding utf8 =head1 NAME IO::All::DBM - DBM Support for IO::All =head1 SYNOPSIS See L. =head1 DESCRIPTION =head1 AUTHOR Ingy döt Net =head1 COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html =cut 1; Dir.pm100644001750001750 1244212267312543 14522 0ustar00frewfrew000000000000IO-All-0.54/lib/IO/Allpackage IO::All::Dir; use strict; use warnings; use IO::All::Filesys -base; use IO::All -base; use IO::Dir; #=============================================================================== const type => 'dir'; option 'sort' => 1; chain filter => undef; option 'deep'; field 'chdir_from'; #=============================================================================== sub dir { my $self = shift; bless $self, __PACKAGE__; if (@_ && @_ > 1) { $self->name( $self->_spec_class->catdir( ($self->pathname ? ($self->pathname) : () ), @_, ) ) } elsif (@_) { $self->name($_[0]) } return $self->_init; } sub dir_handle { my $self = shift; bless $self, __PACKAGE__; $self->_handle(shift) if @_; return $self->_init; } #=============================================================================== sub assert_open { my $self = shift; return if $self->is_open; $self->open; } sub open { my $self = shift; $self->is_open(1); $self->assert_dirpath($self->pathname) if $self->pathname and $self->_assert; my $handle = IO::Dir->new; $self->io_handle($handle); $handle->open($self->pathname) or $self->throw($self->open_msg); return $self; } sub open_msg { my $self = shift; my $name = defined $self->pathname ? " '" . $self->pathname . "'" : ''; return qq{Can't open directory$name:\n$!}; } #=============================================================================== sub All { my $self = shift; $self->all(0); } sub all { my $self = shift; my $depth = @_ ? shift(@_) : $self->_deep ? 0 : 1; my $first = not @_; my @all; while (my $io = $self->next) { push @all, $io; push(@all, $io->all($depth - 1, 1)) if $depth != 1 and $io->is_dir; } @all = grep {&{$self->filter}} @all if $self->filter; return @all unless $first and $self->_sort; return sort {$a->pathname cmp $b->pathname} @all; } sub All_Dirs { my $self = shift; $self->all_dirs(0); } sub all_dirs { my $self = shift; grep {$_->is_dir} $self->all(@_); } sub All_Files { my $self = shift; $self->all_files(0); } sub all_files { my $self = shift; grep {$_->is_file} $self->all(@_); } sub All_Links { my $self = shift; $self->all_links(0); } sub all_links { my $self = shift; grep {$_->is_link} $self->all(@_); } sub chdir { my $self = shift; require Cwd; $self->chdir_from(Cwd::cwd()); CORE::chdir($self->pathname); return $self; } sub empty { my $self = shift; my $dh; opendir($dh, $self->pathname) or die; while (my $dir = readdir($dh)) { return 0 unless $dir =~ /^\.{1,2}$/; } return 1; } sub mkdir { my $self = shift; defined($self->perms) ? (CORE::mkdir($self->pathname, $self->perms) or die "mkdir failed: $!") : (CORE::mkdir($self->pathname) or die "mkdir failed: $!"); return $self; } sub mkpath { my $self = shift; require File::Path; File::Path::mkpath($self->pathname, @_); return $self; } sub file { my ($self, @rest) = @_; return $self->constructor->()->file($self->pathname, @rest) } sub next { my $self = shift; $self->assert_open; my $name = $self->readdir; return unless defined $name; my $io = $self->constructor->(File::Spec->catfile($self->pathname, $name)); $io->absolute if $self->is_absolute; return $io; } sub readdir { my $self = shift; $self->assert_open; if (wantarray) { my @return = grep { not /^\.{1,2}$/ } $self->io_handle->read; $self->close; return @return; } my $name = '.'; while ($name =~ /^\.{1,2}$/) { $name = $self->io_handle->read; unless (defined $name) { $self->close; return; } } return $name; } sub rmdir { my $self = shift; rmdir $self->pathname; } sub rmtree { my $self = shift; require File::Path; File::Path::rmtree($self->pathname, @_); } sub glob { my ($self, @rest) = @_; map {; my $ret = $self->constructor->($_); $ret->absolute if $self->is_absolute; $ret } glob $self->_spec_class->catdir( $self->pathname, @rest ); } sub DESTROY { my $self = shift; CORE::chdir($self->chdir_from) if $self->chdir_from; # $self->SUPER::DESTROY(@_); } #=============================================================================== sub overload_table { ( '${} dir' => 'overload_as_scalar', '@{} dir' => 'overload_as_array', '%{} dir' => 'overload_as_hash', ) } sub overload_as_scalar { \ $_[1]; } sub overload_as_array { [ $_[1]->all ]; } sub overload_as_hash { +{ map { (my $name = $_->pathname) =~ s/.*[\/\\]//; ($name, $_); } $_[1]->all }; } =encoding utf8 =head1 NAME IO::All::Dir - Directory Support for IO::All =head1 SYNOPSIS See L. =head1 DESCRIPTION =head1 AUTHOR Ingy döt Net =head1 COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html =cut 1; file_subclass.t100644001750001750 104312267312543 15102 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; use warnings; use Test::More tests => 5; use IO_Dumper; use IO_All_Test; my $hash = { red => 'square', yellow => 'circle', pink => 'triangle', }; my $io = io->file(o_dir() . '/dump2')->dump($hash); ok(-f o_dir() . '/dump2'); ok($io->close); ok(-s o_dir() . '/dump2'); my $VAR1; my $a = do (o_dir() . '/dump2'); my $b = eval join('',); is_deeply($a,$b); ok($io->unlink); del_output_dir(); package main; __END__ $VAR1 = { 'pink' => 'triangle', 'red' => 'square', 'yellow' => 'circle' }; pkg000755001750001750 012267312543 12257 5ustar00frewfrew000000000000IO-All-0.54manifest.skip100644001750001750 3512267312543 15053 0ustar00frewfrew000000000000IO-All-0.54/pkgREADME.md method_list ^unit/ Base.pm100644001750001750 1122612267312543 14655 0ustar00frewfrew000000000000IO-All-0.54/lib/IO/Allpackage IO::All::Base; use strict; use warnings; use Fcntl; sub import { my $class = shift; my $flag = $_[0] || ''; my $package = caller; no strict 'refs'; if ($flag eq '-base') { push @{$package . "::ISA"}, $class; *{$package . "::$_"} = \&$_ for qw'field const option chain proxy proxy_open'; } elsif ($flag eq -mixin) { mixin_import(scalar(caller(0)), $class, @_); } else { my @flags = @_; for my $export (@{$class . '::EXPORT'}) { *{$package . "::$export"} = $export eq 'io' ? $class->generate_constructor(@flags) : \&{$class . "::$export"}; } } } sub generate_constructor { my $class = shift; my (@flags, %flags, $key); for (@_) { if (s/^-//) { push @flags, $_; $flags{$_} = 1; $key = $_; } else { $flags{$key} = $_ if $key; } } my $constructor; $constructor = sub { my $self = $class->new(@_); for (@flags) { $self->$_($flags{$_}); } $self->constructor($constructor); return $self; } } sub _init { my $self = shift; $self->io_handle(undef); $self->is_open(0); return $self; } #=============================================================================== # Closure generating functions #=============================================================================== sub option { my $package = caller; my ($field, $default) = @_; $default ||= 0; field("_$field", $default); no strict 'refs'; *{"${package}::$field"} = sub { my $self = shift; *$self->{"_$field"} = @_ ? shift(@_) : 1; return $self; }; } sub chain { my $package = caller; my ($field, $default) = @_; no strict 'refs'; *{"${package}::$field"} = sub { my $self = shift; if (@_) { *$self->{$field} = shift; return $self; } return $default unless exists *$self->{$field}; return *$self->{$field}; }; } sub field { my $package = caller; my ($field, $default) = @_; no strict 'refs'; return if defined &{"${package}::$field"}; *{"${package}::$field"} = sub { my $self = shift; unless (exists *$self->{$field}) { *$self->{$field} = ref($default) eq 'ARRAY' ? [] : ref($default) eq 'HASH' ? {} : $default; } return *$self->{$field} unless @_; *$self->{$field} = shift; }; } sub const { my $package = caller; my ($field, $default) = @_; no strict 'refs'; return if defined &{"${package}::$field"}; *{"${package}::$field"} = sub { $default }; } sub proxy { my $package = caller; my ($proxy) = @_; no strict 'refs'; return if defined &{"${package}::$proxy"}; *{"${package}::$proxy"} = sub { my $self = shift; my @return = $self->io_handle->$proxy(@_); $self->error_check; wantarray ? @return : $return[0]; }; } sub proxy_open { my $package = caller; my ($proxy, @args) = @_; no strict 'refs'; return if defined &{"${package}::$proxy"}; my $method = sub { my $self = shift; $self->assert_open(@args); my @return = $self->io_handle->$proxy(@_); $self->error_check; wantarray ? @return : $return[0]; }; *{"$package\::$proxy"} = (@args and $args[0] eq '>') ? sub { my $self = shift; $self->$method(@_); return $self; } : $method; } sub mixin_import { my $target_class = shift; $target_class = caller(0) if $target_class eq 'mixin'; my $mixin_class = shift or die "Nothing to mixin"; eval "require $mixin_class"; my $pseudo_class = CORE::join '-', $target_class, $mixin_class; my %methods = mixin_methods($mixin_class); no strict 'refs'; no warnings; @{"$pseudo_class\::ISA"} = @{"$target_class\::ISA"}; @{"$target_class\::ISA"} = ($pseudo_class); for (keys %methods) { *{"$pseudo_class\::$_"} = $methods{$_}; } } sub mixin_methods { my $mixin_class = shift; no strict 'refs'; my %methods = all_methods($mixin_class); map { $methods{$_} ? ($_, \ &{"$methods{$_}\::$_"}) : ($_, \ &{"$mixin_class\::$_"}) } (keys %methods); } sub all_methods { no strict 'refs'; my $class = shift; my %methods = map { ($_, $class) } grep { defined &{"$class\::$_"} and not /^_/ } keys %{"$class\::"}; return (%methods); } 1; Link.pm100644001750001750 305312267312543 14657 0ustar00frewfrew000000000000IO-All-0.54/lib/IO/Allpackage IO::All::Link; use strict; use warnings; use IO::All::File -base; const type => 'link'; sub link { my $self = shift; bless $self, __PACKAGE__; $self->name(shift) if @_; $self->_init; } sub readlink { my $self = shift; $self->constructor->(CORE::readlink($self->name)); } sub symlink { my $self = shift; my $target = shift; $self->assert_filepath if $self->_assert; CORE::symlink($target, $self->pathname); } sub AUTOLOAD { my $self = shift; our $AUTOLOAD; (my $method = $AUTOLOAD) =~ s/.*:://; my $target = $self->target; unless ($target) { $self->throw("Can't call $method on symlink"); return; } $target->$method(@_); } sub target { my $self = shift; return *$self->{target} if *$self->{target}; my %seen; my $link = $self; my $new; while ($new = $link->readlink) { my $type = $new->type or return; last if $type eq 'file'; last if $type eq 'dir'; return unless $type eq 'link'; return if $seen{$new->name}++; $link = $new; } *$self->{target} = $new; } =encoding utf8 =head1 NAME IO::All::Link - Symbolic Link Support for IO::All =head1 SYNOPSIS See L. =head1 DESCRIPTION =head1 AUTHOR Ingy döt Net =head1 COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html =cut 1; File.pm100644001750001750 1456212267312543 14670 0ustar00frewfrew000000000000IO-All-0.54/lib/IO/Allpackage IO::All::File; use strict; use warnings; use IO::All::Filesys -base; use IO::All -base; use IO::File; #=============================================================================== const type => 'file'; field tied_file => undef; #=============================================================================== sub file { my $self = shift; bless $self, __PACKAGE__; # should we die here if $self->name is already set and there are args? if (@_ && @_ > 1) { $self->name( $self->_spec_class->catfile( @_ ) ) } elsif (@_) { $self->name($_[0]) } return $self->_init; } sub file_handle { my $self = shift; bless $self, __PACKAGE__; $self->_handle(shift) if @_; return $self->_init; } #=============================================================================== sub assert_filepath { my $self = shift; my $name = $self->pathname or return; my $directory; (undef, $directory) = File::Spec->splitpath($self->pathname); $self->assert_dirpath($directory); } sub assert_open_backwards { my $self = shift; return if $self->is_open; require File::ReadBackwards; my $file_name = $self->pathname; my $io_handle = File::ReadBackwards->new($file_name) or $self->throw("Can't open $file_name for backwards:\n$!"); $self->io_handle($io_handle); $self->is_open(1); } sub assert_open { my $self = shift; return if $self->is_open; $self->mode(shift) unless $self->mode; $self->open; } sub assert_tied_file { my $self = shift; return $self->tied_file || do { eval {require Tie::File}; $self->throw("Tie::File required for file array operations:\n$@") if $@; my $array_ref = do { my @array; \@array }; my $name = $self->pathname; my @options = $self->_rdonly ? (mode => O_RDONLY) : (); push @options, (recsep => "\n"); tie @$array_ref, 'Tie::File', $name, @options; $self->throw("Can't tie 'Tie::File' to '$name':\n$!") unless tied @$array_ref; $self->tied_file($array_ref); }; } sub open { my $self = shift; $self->is_open(1); $self->assert_filepath if $self->_assert; my ($mode, $perms) = @_; $self->mode($mode) if defined $mode; $self->mode('<') unless defined $self->mode; $self->perms($perms) if defined $perms; my @args = ($self->mode); push @args, $self->perms if defined $self->perms; if (defined $self->pathname) { $self->io_handle(IO::File->new); $self->io_handle->open($self->pathname, @args) or $self->throw($self->open_msg); } elsif (defined $self->_handle and not $self->io_handle->opened ) { # XXX Not tested $self->io_handle->fdopen($self->_handle, @args); } $self->set_lock; $self->set_binmode; } my %mode_msg = ( '>' => 'output', '<' => 'input', '>>' => 'append', ); sub open_msg { my $self = shift; my $name = defined $self->pathname ? " '" . $self->pathname . "'" : ''; my $direction = defined $mode_msg{$self->mode} ? ' for ' . $mode_msg{$self->mode} : ''; return qq{Can't open file$name$direction:\n$!}; } #=============================================================================== sub close { my $self = shift; return unless $self->is_open; $self->is_open(0); my $io_handle = $self->io_handle; $self->unlock; $self->io_handle(undef); $self->mode(undef); if (my $tied_file = $self->tied_file) { if (ref($tied_file) eq 'ARRAY') { untie @$tied_file; } else { untie %$tied_file; } $self->tied_file(undef); return 1; } $io_handle->close(@_) if defined $io_handle; return $self; } sub empty { my $self = shift; -z $self->pathname; } sub filepath { my $self = shift; my ($volume, $path) = $self->splitpath; return File::Spec->catpath($volume, $path, ''); } sub getline_backwards { my $self = shift; $self->assert_open_backwards; return $self->io_handle->readline; } sub getlines_backwards { my $self = shift; my @lines; while (defined (my $line = $self->getline_backwards)) { push @lines, $line; } return @lines; } sub head { my $self = shift; my $lines = shift || 10; my @return; $self->close; while ($lines--) { push @return, ($self->getline or last); } $self->close; return wantarray ? @return : join '', @return; } sub tail { my $self = shift; my $lines = shift || 10; my @return; $self->close; while ($lines--) { unshift @return, ($self->getline_backwards or last); } $self->close; return wantarray ? @return : join '', @return; } sub touch { my $self = shift; return $self->SUPER::touch(@_) if -e $self->pathname; return $self if $self->is_open; my $mode = $self->mode; $self->mode('>>')->open->close; $self->mode($mode); return $self; } sub unlink { my $self = shift; unlink $self->pathname; } #=============================================================================== sub overload_table { my $self = shift; ( $self->SUPER::overload_table(@_), 'file > file' => 'overload_file_to_file', 'file < file' => 'overload_file_from_file', '${} file' => 'overload_file_as_scalar', '@{} file' => 'overload_file_as_array', '%{} file' => 'overload_file_as_dbm', ) } sub overload_file_to_file { require File::Copy; File::Copy::copy($_[1]->pathname, $_[2]->pathname); $_[2]; } sub overload_file_from_file { require File::Copy; File::Copy::copy($_[2]->pathname, $_[1]->pathname); $_[1]; } sub overload_file_as_array { $_[1]->assert_tied_file; } sub overload_file_as_dbm { $_[1]->dbm unless $_[1]->isa('IO::All::DBM'); $_[1]->assert_open; } sub overload_file_as_scalar { my $scalar = $_[1]->scalar; return \$scalar; } =encoding utf8 =head1 NAME IO::All::File - File Support for IO::All =head1 SYNOPSIS See L. =head1 DESCRIPTION =head1 AUTHOR Ingy döt Net =head1 COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html =cut 1; Temp.pm100644001750001750 145112267312543 14667 0ustar00frewfrew000000000000IO-All-0.54/lib/IO/Allpackage IO::All::Temp; use strict; use warnings; use IO::All::File -base; sub temp { my $self = shift; bless $self, __PACKAGE__; my $temp_file = IO::File::new_tmpfile() or $self->throw("Can't create temporary file"); $self->io_handle($temp_file); $self->error_check; $self->autoclose(0); $self->is_open(1); return $self; } =encoding utf8 =head1 NAME IO::All::Temp - Temporary File Support for IO::All =head1 SYNOPSIS See L. =head1 DESCRIPTION =head1 AUTHOR Ingy döt Net =head1 COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html =cut 1; Pipe.pm100644001750001750 314412267312543 14660 0ustar00frewfrew000000000000IO-All-0.54/lib/IO/Allpackage IO::All::Pipe; use strict; use warnings; use IO::All -base; use IO::File; const type => 'pipe'; sub pipe { my $self = shift; bless $self, __PACKAGE__; $self->name(shift) if @_; return $self->_init; } sub assert_open { my $self = shift; return if $self->is_open; $self->mode(shift) unless $self->mode; $self->open; } sub open { my $self = shift; $self->is_open(1); require IO::Handle; $self->io_handle(IO::Handle->new) unless defined $self->io_handle; my $command = $self->name; $command =~ s/(^\||\|$)//; my $mode = shift || $self->mode || '<'; my $pipe_mode = $mode eq '>' ? '|-' : $mode eq '<' ? '-|' : $self->throw("Invalid usage mode '$mode' for pipe"); CORE::open($self->io_handle, $pipe_mode, $command); $self->set_binmode; } my %mode_msg = ( '>' => 'output', '<' => 'input', '>>' => 'append', ); sub open_msg { my $self = shift; my $name = defined $self->name ? " '" . $self->name . "'" : ''; my $direction = defined $mode_msg{$self->mode} ? ' for ' . $mode_msg{$self->mode} : ''; return qq{Can't open pipe$name$direction:\n$!}; } =encoding utf8 =head1 NAME IO::All::Pipe - Pipe Support for IO::All =head1 SYNOPSIS See L. =head1 DESCRIPTION =head1 AUTHOR Ingy döt Net =head1 COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html =cut 1; dir2000755001750001750 012267312543 13725 5ustar00frewfrew000000000000IO-All-0.54/t/mydirfile1100644001750001750 2012267312543 14740 0ustar00frewfrew000000000000IO-All-0.54/t/mydir/dir2file1 is fun yo dir1000755001750001750 012267312543 13724 5ustar00frewfrew000000000000IO-All-0.54/t/mydirfile1100644001750001750 2012267312543 14737 0ustar00frewfrew000000000000IO-All-0.54/t/mydir/dir1file1 is fun yo STDIO.pm100644001750001750 250512267312543 14645 0ustar00frewfrew000000000000IO-All-0.54/lib/IO/Allpackage IO::All::STDIO; use strict; use warnings; use IO::All -base; use IO::File; const type => 'stdio'; sub stdio { my $self = shift; bless $self, __PACKAGE__; return $self->_init; } sub stdin { my $self = shift; $self->open('<'); return $self; } sub stdout { my $self = shift; $self->open('>'); return $self; } sub stderr { my $self = shift; $self->open_stderr; return $self; } sub open { my $self = shift; $self->is_open(1); my $mode = shift || $self->mode || '<'; my $fileno = $mode eq '>' ? fileno(STDOUT) : fileno(STDIN); $self->io_handle(IO::File->new); $self->io_handle->fdopen($fileno, $mode); $self->set_binmode; } sub open_stderr { my $self = shift; $self->is_open(1); $self->io_handle(IO::File->new); $self->io_handle->fdopen(fileno(STDERR), '>') ? $self : 0; } # XXX Add overload support =encoding utf8 =head1 NAME IO::All::STDIO - STDIO Support for IO::All =head1 SYNOPSIS See L. =head1 DESCRIPTION =head1 AUTHOR Ingy döt Net =head1 COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html =cut 1; MLDBM.pm100644001750001750 261012267312543 14613 0ustar00frewfrew000000000000IO-All-0.54/lib/IO/Allpackage IO::All::MLDBM; use strict; use warnings; use IO::All::DBM -base; field _serializer => 'Data::Dumper'; sub mldbm { my $self = shift; bless $self, __PACKAGE__; my ($serializer) = grep { /^(Storable|Data::Dumper|FreezeThaw)$/ } @_; $self->_serializer($serializer) if defined $serializer; my @dbm_list = grep { not /^(Storable|Data::Dumper|FreezeThaw)$/ } @_; $self->_dbm_list([@dbm_list]); return $self; } sub tie_dbm { my $self = shift; my $filename = $self->name; my $dbm_class = $self->_dbm_class; my $serializer = $self->_serializer; eval "use MLDBM qw($dbm_class $serializer)"; $self->throw("Can't open '$filename' as MLDBM:\n$@") if $@; my $hash; my $db = tie %$hash, 'MLDBM', $filename, $self->mode, $self->perms, @{$self->_dbm_extra} or $self->throw("Can't open '$filename' as MLDBM file:\n$!"); $self->add_utf8_dbm_filter($db) if $self->_utf8; $self->tied_file($hash); } =encoding utf8 =head1 NAME IO::All::MLDBM - MLDBM Support for IO::All =head1 SYNOPSIS See L. =head1 DESCRIPTION =head1 AUTHOR Ingy döt Net =head1 COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html =cut 1; inline_subclass.t100644001750001750 145512267312543 15450 0ustar00frewfrew000000000000IO-All-0.54/tuse lib 't', 'lib'; use strict; package IO::Dumper; use IO::All -base; use Data::Dumper; our @EXPORT = 'io'; sub io { return IO::Dumper->new(@_) }; package IO::All::Filesys; sub dump { my $self = shift; $self->print(Data::Dumper::Dumper(@_)); return $self; } package main; use Test::More tests => 5; use IO_All_Test; IO::Dumper->import; my $hash = { red => 'square', yellow => 'circle', pink => 'triangle', }; die if -f o_dir() . '/dump1'; my $io = io(o_dir() . '/dump1')->file->dump($hash); ok(-f o_dir() . '/dump1'); ok($io->close); ok(-s o_dir() . '/dump1'); my $VAR1; my $a = do (o_dir() . '/dump1'); my $b = eval join('',); is_deeply($a,$b); ok($io->unlink); del_output_dir(); __END__ $VAR1 = { 'pink' => 'triangle', 'red' => 'square', 'yellow' => 'circle' }; String.pm100644001750001750 147112267312543 15232 0ustar00frewfrew000000000000IO-All-0.54/lib/IO/Allpackage IO::All::String; use strict; use warnings; use IO::All -base; use IO::String; const type => 'string'; proxy 'string_ref'; sub string { my $self = shift; bless $self, __PACKAGE__; $self->_init; } sub open { my $self = shift; $self->io_handle(IO::String->new); $self->set_binmode; $self->is_open(1); } =encoding utf8 =head1 NAME IO::All::String - String IO Support for IO::All =head1 SYNOPSIS See L. =head1 DESCRIPTION =head1 AUTHOR Ingy döt Net =head1 COPYRIGHT Copyright (c) 2004. Brian Ingerson. All rights reserved. Copyright (c) 2006, 2008. Ingy döt Net. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html =cut 1; Socket.pm100644001750001750 672012267312543 15216 0ustar00frewfrew000000000000IO-All-0.54/lib/IO/Allpackage IO::All::Socket; use strict; use warnings; use IO::All -base; use IO::Socket; const type => 'socket'; field _listen => undef; option 'fork'; const domain_default => 'localhost'; chain domain => undef; chain port => undef; proxy_open 'recv'; proxy_open 'send'; sub socket { my $self = shift; bless $self, __PACKAGE__; $self->name(shift) if @_; return $self->_init; } sub socket_handle { my $self = shift; bless $self, __PACKAGE__; $self->_handle(shift) if @_; return $self->_init; } sub accept { my $self = shift; use POSIX ":sys_wait_h"; sub REAPER { while (waitpid(-1, WNOHANG) > 0) {} $SIG{CHLD} = \&REAPER; } local $SIG{CHLD}; $self->_listen(1); $self->assert_open; my $server = $self->io_handle; my $socket; while (1) { $socket = $server->accept; last unless $self->_fork; next unless defined $socket; $SIG{CHLD} = \&REAPER; my $pid = CORE::fork; $self->throw("Unable to fork for IO::All::accept") unless defined $pid; last unless $pid; close $socket; undef $socket; } close $server if $self->_fork; my $io = ref($self)->new->socket_handle($socket); $io->io_handle($socket); $io->is_open(1); return $io; } sub shutdown { my $self = shift; my $how = @_ ? shift : 2; my $handle = $self->io_handle; $handle->shutdown(2) if defined $handle; } sub assert_open { my $self = shift; return if $self->is_open; $self->mode(shift) unless $self->mode; $self->open; } sub open { my $self = shift; return if $self->is_open; $self->is_open(1); $self->get_socket_domain_port; my @args = $self->_listen ? ( LocalAddr => $self->domain, LocalPort => $self->port, Proto => 'tcp', Listen => 1, Reuse => 1, ) : ( PeerAddr => $self->domain, PeerPort => $self->port, Proto => 'tcp', ); my $socket = IO::Socket::INET->new(@args) or $self->throw("Can't open socket"); $self->io_handle($socket); $self->set_binmode; } sub get_socket_domain_port { my $self = shift; my ($domain, $port); ($domain, $port) = split /:/, $self->name if defined $self->name; $self->domain($domain) unless defined $self->domain; $self->domain($self->domain_default) unless $self->domain; $self->port($port) unless defined $self->port; return $self; } sub overload_table { my $self = shift; ( $self->SUPER::overload_table(@_), '&{} socket' => 'overload_socket_as_code', ) } sub overload_socket_as_code { my $self = shift; sub { my $coderef = shift; while ($self->is_open) { $_ = $self->getline; &$coderef($self); } } } sub overload_any_from_any { my $self = shift; $self->SUPER::overload_any_from_any(@_); $self->close; } sub overload_any_to_any { my $self = shift; $self->SUPER::overload_any_to_any(@_); $self->close; } =encoding utf8 =head1 NAME IO::All::Socket - Socket Support for IO::All =head1 SYNOPSIS See L. =head1 DESCRIPTION =head1 AUTHOR Ingy döt Net =head1 COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008, 2010. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html =cut 1; Filesys.pm100644001750001750 577212267312543 15412 0ustar00frewfrew000000000000IO-All-0.54/lib/IO/Allpackage IO::All::Filesys; use strict; use warnings; use IO::All::Base -base; use Fcntl qw(:flock); my %spec_map = ( unix => 'Unix', win32 => 'Win32', vms => 'VMS', mac => 'Mac', os2 => 'OS2', ); sub os { my ($self, $type) = @_; my ($v, $d, $f) = $self->_spec_class->splitpath($self->name); my @d = $self->_spec_class->splitdir($d); $self->_spec_class($spec_map{$type}); $self->name( $self->_spec_class->catfile( @d, $f ) ); return $self } sub exists { my $self = shift; -e $self->name } sub filename { my $self = shift; my $filename; (undef, undef, $filename) = $self->splitpath; return $filename; } sub ext { my $self = shift; return $1 if $self->filename =~ m/\.([^\.]+)$/ } { no warnings 'once'; *extension = \&ext; } sub mimetype { require File::MimeInfo; return File::MimeInfo::mimetype($_[0]->filename) } sub is_absolute { my $self = shift; return *$self->{is_absolute} = shift if @_; return *$self->{is_absolute} if defined *$self->{is_absolute}; *$self->{is_absolute} = IO::All::is_absolute($self) ? 1 : 0; } sub is_executable { my $self = shift; -x $self->name } sub is_readable { my $self = shift; -r $self->name } sub is_writable { my $self = shift; -w $self->name } { no warnings 'once'; *is_writeable = \&is_writable; } sub pathname { my $self = shift; return *$self->{pathname} = shift if @_; return *$self->{pathname} if defined *$self->{pathname}; return $self->name; } sub relative { my $self = shift; $self->pathname(File::Spec->abs2rel($self->pathname)) if $self->is_absolute; $self->is_absolute(0); return $self; } sub rename { my $self = shift; my $new = shift; rename($self->name, "$new") ? UNIVERSAL::isa($new, 'IO::All') ? $new : $self->constructor->($new) : undef; } sub set_lock { my $self = shift; return unless $self->_lock; my $io_handle = $self->io_handle; my $flag = $self->mode =~ /^>>?$/ ? LOCK_EX : LOCK_SH; flock $io_handle, $flag; } sub stat { my $self = shift; return IO::All::stat($self, @_) if $self->is_open; CORE::stat($self->pathname); } sub touch { my $self = shift; $self->utime; } sub unlock { my $self = shift; flock $self->io_handle, LOCK_UN if $self->_lock; } sub utime { my $self = shift; my $atime = shift; my $mtime = shift; $atime = time unless defined $atime; $mtime = $atime unless defined $mtime; utime($atime, $mtime, $self->name); return $self; } =encoding utf8 =head1 NAME IO::All::Filesys - File System Methods Mixin for IO::All =head1 SYNOPSIS See L. =head1 DESCRIPTION =head1 AUTHOR Ingy döt Net =head1 COPYRIGHT Copyright (c) 2004. Brian Ingerson. Copyright (c) 2006, 2008. Ingy döt Net. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html =cut release-pod-syntax.t100644001750001750 45012267312543 15771 0ustar00frewfrew000000000000IO-All-0.54/t#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } use Test::More; eval "use Test::Pod 1.41"; plan skip_all => "Test::Pod 1.41 required for testing POD" if $@; all_pod_files_ok(); examples000755001750001750 012267312543 13314 5ustar00frewfrew000000000000IO-All-0.54create-cat-to.pl100644001750001750 37412267312543 16425 0ustar00frewfrew000000000000IO-All-0.54/examples#!/usr/bin/perl # create-cat-to.pl # cat to a file that can be created. use strict; use warnings; use IO::All; my $filename = shift(@ARGV); # Create a file called $filename, including all leading components. io('-') > io->file($filename)->assert; dirx000755001750001750 012267312543 15611 5ustar00frewfrew000000000000IO-All-0.54/t/mydir/dir1/dirafile1100644001750001750 512267312543 16607 0ustar00frewfrew000000000000IO-All-0.54/t/mydir/dir1/dira/dirxtest