Pipelining

Julia defines a pipeline function to redirect the output of a command as the input to the following command:

run(pipeline(`cat $file`,"test.txt"))  

This writes the contents of the file referred to by $file into test.txt, which is shown as follows:

run(pipeline("test.txt",`cat`)) 

This pipeline function can even take several successive commands, as follows:

run(pipeline(`echo $("
hi
Julia")`,`cat`,`grep -n J`)) #> 
3:Julia

If the file tosort.txt contains B, A, and C on consecutive lines, then the following command will sort the lines:

run(pipeline(`cat "tosort.txt"`,`sort`))  # returns A B C 

Another example is to search for the word is in all the text files in the current folder. Use the following command:

run(`grep is $(readdir())`) 

To capture the result of a command in Julia, use read or readline:

a = read(pipeline(`cat "tosort.txt"`,`sort`))

Now a has the value A B C .

Multiple commands can be run in parallel with the & operator:

run(`cat "file1.txt"` & `cat "tosort.txt"`) 

This will print the lines of the two files intermingled, because the printing happens concurrently.

Using this functionality requires careful testing, and, probably, the code will differ according to the operating system on which your Julia program runs. You can obtain the OS from the variable Sys.KERNEL, or use the functions iswindows, isunix, islinux, and isosx from the Sys package, which was specifically designed to handle platform variations. For example, let's say we want to execute the function fun1() (unless we are on Windows, in which case the function is fun2()). We can write this as follows:

Sys.iswindows() ? fun1 : fun2  

Or we can write it with the more usual if...else keyword:

if Sys.iswindows()  
    fun1 
else 
    fun2 
end 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.249.252