💾 Archived View for thrig.me › blog › 2024 › 04 › 17 › tiehandle.pl captured on 2024-05-10 at 12:05:58.

View Raw

More Information

-=-=-=-=-=-=-

#!/usr/bin/env perl
use 5.36.0;

package FailFH {
    use Errno qw(EBADF);

    sub creat ( $data, $limit ) {
        \do { local *H; tie *H, FailFH => $data, $limit; *H }
    }

    sub TIEHANDLE {
        my ( $class, $data, $limit ) = @_;
        bless { data => $data, limit => $limit, offset => 0, }, $class;
    }

    sub READ {
        my ( $self, undef, $len ) = @_;
        my $remains = $self->{limit} - $self->{offset};
        if ( $remains <= 0 ) {
            $! = EBADF;
            return undef;
        }
        $len  = $remains if $remains < $len;
        $_[1] = substr $self->{data}, $self->{offset}, $len;
        $self->{offset} += $len;
        return $len;
    }
}

my $fh = FailFH::creat foobar => 3;
my $buf;

read $fh, $buf, 3;
say $buf;    # okay, read 'foo'

read $fh, $buf, 3;
say $!;      # not okay, got EBADF