Is there a way to get notified when "print" is called on $ fh?

When I do this:

print $fh 'text';

I need to call &sub.

Is there any way to do this?

+4
source share
3 answers

You can tiehandle the file descriptor and configure the behavior for printing on this file descriptor or for any other operation on this file descriptor.

sub PrintNotifier::TIEHANDLE {
    my ($pkg, $orignalHandle) = @_;
    bless { glob => $orignalHandle }, $pkg;
}
sub PrintNotifier::PRINT {
    my ($self,@msg) = @_;
    ... do whatever you want with @msg here ...
    return print {$self->{glob}} @msg;
}
sub PrintNotifier::CLOSE { return close $_[0]->{glob} }

open my $fh, '>', 'some-file';
tie *$fh, 'PrintNotifier', $fh;
print $fh "something";           # calls  PrintNotifier::PRINT
+4
source

You can tiehandle it as the crowd suggested. Or, if you can change the code and your Perl is new enough, you can replace

print $fh 'text';

from

$fh->print('text');

which you might consider a cleaner syntax; then you can subclass IO :: File:

package MyFH {
    use parent qw/ IO::File /;
    use mro; # Get next::method

    sub print {
        my ($self, @args) = @_;

        warn 'Printing ', @args;
        $self->next::method(@args);
    }
}

my $fh = MyFH->new();
$fh->open('file', '>') or die $!;

However, this does not fix the old-fashioned

print $fh 'text';

style.

, ,

$obj->method()->print('text');

print {$obj->method()} 'text';

Perl 5.14 , Perls ( ) 5.8,

use IO::Handle;

, ( ).

+2

In perl, use

, :

tie *$self, $self;
print $self 'text';
$self->print( 'text' );
0

Source: https://habr.com/ru/post/1609667/


All Articles