[...] use Carp; use Scalar::Util qw(openhandle); [...] sub read_value { my $input = shift; my $length = shift; if (ref $input eq 'SCALAR') { return _read_value_from_sref($input, $length); } elsif (defined openhandle($input)) { return _read_value_from_fh($input, $length); } else { croak("Invalid usage!\n"); } } sub _read_value_from_fh { my $fh = shift; my $length = shift; my $curpos = tell $fh; my $filelength = (stat $fh)[7]; if ($curpos + $length > $filelength) { # can not read beyond end of file return; } if (read $fh, (my $value), $length) { return $value; } # don't know how to provoke the else-branch for testing else { carp("Something bad happened!\n"); # try to return to previous position seek $fh, 0, $curpos; return; } }