Backticks
Friday, July 15, 2016
Most languages support running arbitrary commands using something like the Linux system function. Often, this support has both quick-and-easy and full-featured-but-complex versions.
In Python, you can use os.system:
>>> os.system("ls -l")
In Ruby, you can use system as well as “backticks”:
irb(main):001:0> system("ls -l")
irb(main):002:0> `ls -l`
Basically, the difference between “system” and “backticks” is:
- “system” executes a command, returning the exit code of the process.
- “backticks” executes a command, returning the standard output of the process.
Factor has extensive cross-platform support for launching processes, but I thought it would be fun to show how custom syntax can be created to implement “backticks”, capturing and returning standard output from the process:
SYNTAX: `
"`" parse-multiline-string '[
_ utf8 [ contents ] with-process-reader
] append! ;
You can use this in a similar fashion to Ruby or Perl:
IN: scratchpad ` ls -l`
Note: This syntax currently requires a space after the leading backtick. In the future, we have plans for an improved lexer that removes this requirement.
This is available in the backticks vocabulary.