http://www.perlmonks.org?node_id=1210469

mdamazon has asked for the wisdom of the Perl Monks concerning the following question:

I think there is a Perl module to do this, but I can't seem to find a reference to it. What I want to do is exit backticks early. So, rather than returning 1000 rows, it only returns the first x number of rows. The point of my wanting to do this is speed of execution. Any ideas you can point me towards? Thanks!

Replies are listed 'Best First'.
Re: Exiting backticks early
by salva (Canon) on Mar 07, 2018 at 19:23 UTC
    Open the child process as a pipe, read as many lines as you want, then kill it.
    my $pid = open my $fh, '-|', $cmd, @args; my @ten_lines; for (0..9) { my $line = <$fh> // last; push @ten_lines, $line; } kill TERM => $pid;
Re: Exiting backticks early
by LanX (Saint) on Mar 07, 2018 at 19:16 UTC

      Well cat | head -n3 prints "cat: write error: No space left on device" on stderr and terminates when I type a fourth line so the writing process can be terminated (though I'm sure there are exceptions). Tested with cygwin on Windows BTW

      Isn't killing the feeding process done by SIGPIPE handling?
      $ perl -e ' @a = `cat /etc/passwd | head -3 `; print for @a' root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin $ ps auxww | fgrep 'cat /etc/passwd' bobn 26404 0.0 0.0 9376 764 pts/10 S+ 13:11 0:00 fgrep + --color=auto cat /etc/passwd $

      --Bob Niederman,

      All code given here is UNTESTED unless otherwise stated.

A reply falls below the community's threshold of quality. You may see it by logging in.