in reply to Re^2: Inheritance and IO
in thread Inheritance and IO

It's not that much effort :)   You could start with just the READLINE method, and add more functionality later, if the need should arise...

Here's a simple example implementing READLINE and PRINT functionality:

#!/usr/bin/perl package MyFH; sub TIEHANDLE { my $class = shift; return bless { @_ }, $class; } sub READLINE { my $self = shift; print "reading line from remote file $self->{file} ...\n"; # ... (your implementation here) my $line = "foo\n"; my @lines = ("foo1\n", "foo2\n"); return wantarray ? @lines : $line; } sub PRINT { my $self = shift; print "writing line(s) to remote file $self->{file} ...\n"; # ... (your implementation here) print "wrote: @_\n"; } package main; use Symbol 'gensym'; my $fh = gensym(); # get ref to anonymous glob tie *$fh, "MyFH", "file" => "foo.txt"; my $line = <$fh>; print "read: $line\n"; print $fh "bar", "baz";

Outputs:

reading line from remote file foo.txt ... read: foo writing line(s) to remote file foo.txt ... wrote: bar baz

(Similarly, you could make use of Tie::Handle / Tie::StdHandle)

 

Update: the benefit of using a tied filehandle would also be that you could more easily make your remote SSH connection handle act like a full-fledged drop-in replacement for a regular filehandle, so existing code making use of <$fh> and print $fh ..., etc. wouldn't have to be modified. This might not seem important now, but who knows when you'll need it...

While you can overload the diamond operator, attempting to override/redefine print would soon turn into a major show stopper. Problem is that the print built-in doesn't have a prototype, at least not one that you could express with Perl's current prototyping mechanism (for this reason prototype 'CORE::print' is returning undef, btw). Its implicit prototype has been coded right into Perl's parser. This means that you cannot write a regular Perl subroutine which would be treated syntactically like the built-in print. In particular you can't get the "comma being absent" after the $fh in print $fh @args to work as desired (you'd get a syntax error if you tried).  With a tied filehandle you don't have such problems.