Perl: sysread on a file descriptor in memory?

This, unfortunately, does not work:

my $input = "this is a test"; open(my $fh, "<", \$input); my $n = sysread($fh, $buf, 4); # want $n == 4, $buf eq 'this' 

Replacing sysread with read works as expected.

Is this expected? Is it possible to make it work? Did I miss something?

+4
source share
2 answers

After sysread, the variable $! contain "Bad file descriptor"? Then you may have encountered error 72428 "sysread does not work with a file descriptor for a scalar" ( https://rt.perl.org/rt3/Public/Bug/Display.html?id=72428 )

+5
source

This works, however, I don’t quite understand why, or if you really want to do it.

 my $input = "this is a test"; open(my $fh,'-|',"echo $a"); # open a pipe instead and echo the string my $n = sysread($fh,$buf,4) or warn $!; 

Note that crashing sysread sets $! so you can check for errors.

+1
source

All Articles