Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Exiting backticks early

by mdamazon (Acolyte)
on Mar 07, 2018 at 18:50 UTC ( #1210469=perlquestion: print w/replies, xml ) Need Help??
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 (Abbot) 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 (Archbishop) 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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1210469]
Approved by Corion
Front-paged by haukex
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (9)
As of 2019-01-17 15:43 GMT
Find Nodes?
    Voting Booth?
    After Perl5, I'm mostly interested in:

    Results (309 votes). Check out past polls.