[Melbourne-pm] Promoting old-school file handles to io::handles

Toby Corkindale toby.corkindale at strategicdata.com.au
Mon Jan 11 23:09:24 PST 2010


Alfie John wrote:
> Hey Toby,
> 
> When you use IO::Handle etc, all regular handles are automagically 
> blessed into IO::Handle objects:
> 
> -- 8< --
> 
>   $ perl -we 'use IO::File; open my $fh, ">test.txt"; $fh->print( "hello 
> world" )'
>   $ cat test.txt
>   Hello world
> 
> -- >8 --
> 
> Pretty elegant huh :)

I had seen someone else mention that, but when I tried it, it failed - I 
think because you need to "use IO::File" in the calling class before 
opening the file -- and I don't have control over the calling code.

> As for FileHandle, haven't used it. Would subclassing FileHandle do what 
> you want? All that Moose stuff looks a bit ugly.

Hmm, same problem as above -- how to deal with not having control over 
the point where it's opened, just receiving the parameter into your code.

thanks!
Toby

> On Tue, Jan 12, 2010 at 5:29 PM, Toby Corkindale 
> <toby.corkindale at strategicdata.com.au 
> <mailto:toby.corkindale at strategicdata.com.au>> wrote:
> 
>     Old-school Perl file handles looked like this:
> 
>      open(INPUT, "<$filename");
> 
>     Then later they could be:
> 
>      open(my $input, "<$filename");
> 
>     New-school filehandles are:
> 
>      my $input = IO::File->new($filename, 'r');
> 
>     And interregnum filehandles were:
> 
>      my $fh = FileHandle->new($filename, 'r');
> 
>     I want to have a method which accepts all, but operates upon them
>     using new-school object methods, ie. $file->autoflush(1) or
>     $file->input_line_number;
> 
> 
>     Currently I'm doing it via the following simplified code example,
>     but I wondered if there was a more elegant solution?
> 
> 
>     package Thingy;
>     use Moose;
>     use IO::Handle;
> 
>     has 'input' => (
>      is => 'rw',
>      isa => 'FileHandle', # Native Moose type, not same as FileHandle
>     );
> 
>     around 'BUILDARGS' => sub {
>      my ($orig, $class, $args) = @_;
>      unless (blessed $args{input} and $args{input}->isa('IO::Handle')) {
>        $args->{input} = IO::Handle->new->fdopen(fileno($args->{input}));
>      }
>      return $args;
>     };
>     _______________________________________________
>     Melbourne-pm mailing list
>     Melbourne-pm at pm.org <mailto:Melbourne-pm at pm.org>
>     http://mail.pm.org/mailman/listinfo/melbourne-pm
> 
> 


-- 
Strategic Data Pty Ltd
Ph: 03 9340 9000


More information about the Melbourne-pm mailing list