The python exception is raised since the reading process (head
) closes its end so the script receives SIGPIPE
the next time it attempts to write; see this post. This involved decisions in Python community, to change defaults so to inform the user (see the linked post).
This is not seen in Perl because it gets killed by that signal (what is its disposition) without saying anything. So you could override that
use warnings;
$| = 1;
$SIG{PIPE} = sub { die $! };
for my $i (0..4_000-1) {
print $i, "\n";
}
(without the $| = 1
I need more than 5_000
above for it to happen.)
Or, rather issue a warn
ing (instead of die
) so that the program continues
local $SIG{PIPE} = sub { warn "Ignoring $_[0]: $!" };
Update Given the clarification provided in a comment I'd recommend this handler to be global in fact. It can still be overriden with a local
one in particular scopes. Besides, there is nothing wrong with surviving a SIGPIPE
instead of being terminated, as long as there is a warning.
Note that even without that the exit status of the Perl process will show the problem. Run echo $?
after the process "completes" (is quietly terminated); I get 32
on my system.
To mimic Python's behavior further you could issue a die
in the signal handler and handle that exception, by putting it all in eval
.
Thanks to melpomene and ikegami for comments.