1

Quick question,

Is there a way to pipe a command into another command via perl like you can in the *Nix command line?

For example:
free -m | grep Mem

How would I be able to do the "piping" in Perl?

drewrockshard
  • 2,043
  • 10
  • 35
  • 47

1 Answers1

6

You can invoke the command exactly like that:

system("free -m | grep Mem");

From the documentation:

If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is /bin/sh -c on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to execvp , which is more efficient.

You can do the same with other methods for invoking external commands, like open:

open my $fh, "-|", "free -m | grep Mem" or croak "failed to run pipeline";
# and now read from $fh as usual
Cascabel
  • 479,068
  • 72
  • 370
  • 318
  • 3
    Better to use the three-argument open: `open my $fh, "-|", "free -m | grep Mem" or croak "Failed to run pipeline";`? – Jonathan Leffler Nov 30 '10 at 21:56
  • Worked great. I actually used Jonathan's recommended way, but the original answer pointed me into the correct direction. – drewrockshard Nov 30 '10 at 22:51
  • @Jonathan: There is abslutely nothing to be gained by the clumsy variadic version in this case. Just write: `$kidpid = open(KIDPIPE, "free -m | grep Mem|") || die "couldn't fork: $!";`. There is no reason to encourage such ugly code that buys you only diminished legibility!! – tchrist Nov 30 '10 at 23:09
  • @tchrist: I'm ashamed to admit that I bowed to the 70k rep and three comment upvotes there. – Cascabel Nov 30 '10 at 23:11
  • 2
    @Jefromi: I don’t have the rep, but I **have** been *Programming Perl* ever since Day 0 back on December 18th, 1987. There is nothing wrong with using 2-argument open when you have a literal string. It’s a lot clearer. – tchrist Nov 30 '10 at 23:18
  • 1
    @Jefromi: my comment was a suggestion - it is echoed by various sources on the web. The two argument version also works; I used to use it, but now I use the three argument version because it avoids ambiguities. I'd have been happy if you'd left your answer alone, leaving my comment there as an alternative suggestion. All a 70K rep means is that I've spent more time on here than some other people. – Jonathan Leffler Dec 01 '10 at 02:49
  • @Jonathan: To be fair, your reputation (particularly the silver perl badge) and your other answers I've seen mean that you're a lot more solid in perl than I am; I do think it's a good suggestion, rep or not, even if it's not strictly necessary. – Cascabel Dec 01 '10 at 02:53
  • The three argument open is recommended by "Perl Best Practices" and the two-argument form will be highlighted by `perlcritic` as the highest severity. See page p207. – Imran-UK Jul 04 '13 at 16:21