The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

IO::Moose::Handle - Reimplementation of IO::Handle with improvements

SYNOPSIS

  use IO::Moose::Handle;

  my $fh = IO::Moose::Handle->new;
  $fh->fdopen( fileno(STDIN) );
  print $fh->getline;
  my $content = $fh->slurp;
  $fh->close;

  my $fh = IO::Moose::Handle->fdopen( \*STDERR, '>' );
  $fh->autoflush(1);
  $fh->say('Some text');
  undef $fh;  # calls close at DESTROY

DESCRIPTION

This class extends IO::Handle with following differences:

  • It is based on Moose object framework.

  • The stat method returns File::Stat::Moose object.

  • It uses Exception::Base for signaling errors. Most of methods are throwing exception on failure.

  • The modifiers like input_record_separator are supported on per file handle basis.

  • It also implements additional methods like say, slurp.

INHERITANCE

EXCEPTIONS

Exception::Argument

Thrown whether method is called with wrong argument.

Exception::Fatal

Thrown whether fatal error is occurred by core function.

ATTRIBUTES

file : Num|FileHandle|OpenHandle {ro}

File (file descriptor number, file handle or IO object) as a parameter for new object or argument for fdopen method.

mode : CanonOpenModeStr {ro} = "<"

File mode as a parameter for new object or argument for fdopen method. Can be Perl-style (<, >, >>, etc.) or C-style (r, w, a, etc.)

fh : GlobRef {ro}

File handle used for internal IO operations.

autochomp : Bool = false {rw}

If is true value the input will be auto chomped.

tainted : Bool = ${^TAINT} {rw}

If is false value and tainted mode is enabled the untaint method will be called after fdopen.

blocking : Bool = true {rw}

If is false value the non-blocking IO will be turned on.

copyfh : Bool = false {ro}

If is true value the file handle will be copy of file argument. If file argument is not a file handle, the Exception::Argument is thrown.

tied : Bool = true {ro}

By default the object's file handle is tied variable, so it can be used with standard, non-OO interface (open, print, getc functions and <> operator). This interface is slow and can be disabled if the OO interface only is used.

strict_accessors : Bool = false {rw}

By default the accessors might be avoided for performance reason. This optimization can be disabled if the attribute is set to true value.

format_formfeed : Str {rw, var="$^L"}
format_line_break_characters : Str {rw, var="$:"}
input_record_separator : Str {rw, var="$/"}
output_field_separator : Str {rw, var="$,"}
output_record_separator : Str {rw, var="$\"}

These are attributes assigned with Perl's built-in variables. See perlvar for complete descriptions. The fields have accessors available as per file handle basis if called as $io->accessor or as global setting if called as IO::Moose::Handle->accessor.

IMPORTS

use IO::Moose::Handle '$STDIN', '$STDOUT', '$STDERR';
use IO::Moose::Handle ':std';
use IO::Moose::Handle ':all';

Creates handle as a copy of standard handle and imports it into caller's namespace. This handles won't be created until explicit import.

  use IO::Moose::Handle ':std';
  print $STDOUT->autoflush(1);
  print $STDIN->slurp;

CONSTRUCTORS

new( args : Hash ) : Self

Creates the IO::Moose::Handle object and calls fdopen method if the mode parameter is defined.

  $io = IO::Moose::Handle->new( file => \*STDIN, mode => "r" );

The object can be created with unopened file handle which can be opened later.

  $in = IO::Moose::Handle->new( file => \*STDIN );
  $in->fdopen("r");

If copyfh is true value and file contains a file handle, this file handle is copied rather than new file handle created.

  $tmp = File::Temp->new;
  $io = IO::Moose::Handle->new( file => $tmp, copyfh => 1, mode => "w" );
new_from_fd( fd : Num|FileHandle|OpenHandle, mode : CanonOpenModeStr = "<") : Self

Creates the IO::Moose::Handle object and immediately opens the file handle based on arguments.

  $out = IO::Moose::Handle->new_from_fd( \*STDOUT, "w" );

METHODS

fdopen( fd : Num|FileHandle|OpenHandle, mode : CanonOpenModeStr = "<" ) : Self

Opens the previously created file handle. If the file was already opened, it is closed automatically and reopened without resetting its line counter. The method also sets the file and mode attributes.

  $out = IO::Moose::Handle->new;
  $out->fdopen( \*STDOUT, "w" );

  $dup = IO::Moose::Handle->new;
  $dup->fdopen( $dup, "a" );

  $stdin = IO::Moose::Handle->new;
  $stdin->fdopen( 0, "r");
close() : Self

Closes the opened file handle. The file and mode attributes are cleared after closing.

eof() : Bool
fileno() : Int
opened() : Bool
print( args : Array ) : Self
printf( fmt : Str = "", args : Array = () ) : Self
sysread( out buf, len : Int, offset : Int = 0 ) : Int
syswrite( buf : Str, len : Int, offset : Int = 0 ) : Int
getc() : Char
read( out buf, len : Int, offset : Int = 0 ) : Int
truncate( len : Int ) : Self

These are front ends for corresponding built-in functions. Most of them throws exception on failure which can be caught with try/catch:

  use Exception::Base;
  eval {
    open $f, "/etc/hostname";
    $io = IO::Moose::Handle->new( file => $f, mode => "r" );
    $c = $io->getc;
  };
  if ($@) {
    my $e = Exception::Base->catch) {
    warn "problem with /etc/hostname file: $e";
  };

The fdopen, close, print, printf and truncate methods returns this object.

write( buf : Str, len : Int, offset : Int = 0 ) : Int

The opposite of read. The wrapper for the perl "write" in perlfunc function is called format_write.

format_write( format_name : Str ) : Self

The wrapper for perl "format" in perlfunc function.

readline() : Maybe[Str|Array]
getline() : Str

The readline method which is called always in scalar context.

  $io = IO::Moose::Handle->new( file=>\*STDIN, mode=>"r" );
  push @a, $io->getline;  # reads only one line
getlines() : Array

The readline method which is called always in array context.

  $io = IO::Moose::Handle->new( file => \*STDIN, mode => "r" );
  print scalar $io->getlines;  # error: can't call in scalar context.
ungetc( ord : Int ) : Self

Pushes a character with the given ordinal value back onto the given handle's input stream.

  $io = IO::Moose::Handle->new( file => \*STDIN, mode => "r" );
  $io->ungetc(ord('A'));
  print $io->getc;  # prints A
say( args : Array ) : Self

The print method with EOL character at the end.

  $io = IO::Moose::Handle->new( file => \*STDOUT, mode => "w" );
  $io->say("Hello!");
IO::Moose::Handle->slurp( file : Num|FileHandle|OpenHandle, args : Hash ) : Str|Array

Creates the IO::Moose::Handle object and returns its content as a scalar in scalar context or as an array in array context.

  open $f, "/etc/passwd";
  $passwd_file = IO::Moose::Handle->slurp($f);

Additional args are passed to IO::Moose::Handle constructor.

slurp() : Str|Array

Reads whole file and returns its content as a scalar in scalar context or as an array in array context (like getlines method).

  open $f, "/etc/passwd";

  $io1 = IO::Moose::Handle->new( file => $f, mode => "r" );
  $passwd_file = $io1->slurp;

  $io2 = IO::Moose::Handle->new( file => $f, mode => "r" );
  $io2->autochomp(1);
  @passwd_lines = $io2->slurp;
stat() : File::Stat::Moose

Returns File::Stat::Moose object which represents status of file pointed by current file handle.

  open $f, "/etc/passwd";
  $io = IO::Moose::Handle->new( file => $f, mode => "r" );
  $st = $io->stat;
  print $st->size;  # size of /etc/passwd file
error() : Bool

Returns true value if the file handle has experienced any errors since it was opened or since the last call to clearerr, or if the handle is invalid.

It is recommended to use exceptions mechanism to handle errors.

clearerr() : Bool

Clear the given handle's error indicator. Returns true value if the file handle is valid or false value otherwise.

sync() : Self

Synchronizes a file's in-memory state with that on the physical medium. It operates on file descriptor and it is low-level operation. Returns this object on success or throws an exception.

flush() : Self

Flushes any buffered data at the perlio API level. Returns self object on success or throws an exception.

printflush( args : Array ) : Self

Turns on autoflush, print args and then restores the autoflush status. Returns self object on success or throws an exception.

blocking() : Bool
blocking( bool : Bool ) : Bool

If called with an argument blocking will turn on non-blocking IO if bool is false, and turn it off if bool is true. blocking will return the value of the previous setting, or the current setting if bool is not given.

untaint() : Self {rw}

Marks the object as taint-clean, and as such data read from it will also be considered taint-clean. It has meaning only if Perl is running in tainted mode (-T).

format_lines_left() : Str {var="$-"}
format_lines_left( value : Str ) : Str {var="$-"}
format_lines_per_page() : Str {var="$="}
format_lines_per_page( value : Str ) : Str {var="$="}
format_page_number() : Str {var="$%"}
format_page_number( value : Str ) : Str {var="$%"}
input_line_number() : Str {var="$."}
input_line_number( value : Str ) : Str {var="$."}
output_autoflush() : Str {var="$|"}
output_autoflush( value : Str ) : Str {var="$|"}
autoflush() : Str {var="$|"}
autoflush( value : Str ) : Str {var="$|"}
format_name() : Str {var="$~"}
format_name( value : Str ) : Str {var="$~"}
format_top_name() : Str {var="$^"}
format_top_name( value : Str ) : Str {var="$^"}

These are accessors assigned with Perl's built-in variables. See perlvar for complete descriptions.

DEBUGGING

The debugging mode can be enabled if PERL_DEBUG_IO_MOOSE_HANDLE environment variable is set to true value. The debugging mode requires Smart::Comments module.

The run-time assertions can be enabled with Test::Assert module.

INTERNALS

This module uses MooseX::GlobRef::Object and stores the object's attributes in glob reference. They can be accessed with *$self->{attr} expression or with standard accessors $self->attr.

There are two handles used for IO operations: the original handle used for real IO operations and tied handle which hooks IO functions interface.

The OO-style uses original handle stored in fh field.

  # Usage:
  $io->print("OO style");

  # Implementation:
  package IO::Moose::Handle;
  sub print {
      my $self = shift;
      CORE::print { $self->fh } @_
  }

The IO functions-style uses object reference which is dereferenced as a handle tied to proxy object which operates on original handle.

  # Usage:
  print $io "IO functions style";

  # Implementation:
  package IO::Moose::Handle;
  sub PRINT { shift()->print(@_) };
  sub print {
      my $self = shift;
      CORE::print { $self->fh } @_
  }

SEE ALSO

IO::Handle, MooseX::GlobRef::Object, Moose.

BUGS

The API is not stable yet and can be changed in future.

AUTHOR

Piotr Roszatycki <dexter@cpan.org>

LICENSE

Copyright 2007, 2008, 2009 by Piotr Roszatycki <dexter@cpan.org>.

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