Perl and PHP do this with backticks. For example,
$output = `ls`;
Returns a directory listing. A similar function, system("foo")
, returns the operating system return code for the given command foo. I'm talking about a variant that returns whatever foo prints to stdout.
How do other languages do this? Is there a canonical name for this function? (I'm going with "backtick"; though maybe I could coin "syslurp".)
Lua:
Haskell:
With MissingH installed:
This is an easy operation in "glue" languages like Perl and Ruby, but Haskell isn't.
C (with
glibc
extension):Okay, not really concise or clean. That's life in C...
Perl, another way:
Useful because you can feed the command input, and get back both stderr and stdout separately. Nowhere near as neat/scary/slow/disturbing as
IPC::Run
, which can set up pipes to subroutines.Granted, it is not the smaller ( from all the languages available ) but it shouldn't be that verbose.
This version is dirty. Exceptions should be handled, reading may be improved. This is just to show how a java version could start.
Complete program below.
Sample ouput ( using the type command )
Sample output ( dir )
Try any
EDIT
I must admit I'm not 100% sure this is the "best" way to do it. Feel free to post references and/or code to show how can it be improved or what's wrong with this.
Yet another way (or 2!) in Perl....
open can also be written like so...