Java Reference
In-Depth Information
The next special global variable that we'll meet is $ENV , that provides an interface to
the current environment variables. For example, to print out the current user's
home directory:
print ( "HOME = " + $ENV . HOME ); # Prints / home / ben for me
Nashorn also provides access to a special global function called $EXEC() . This works
like the backticks we met just now, as this example shows:
var execOutput = $EXEC ( "echo Print this on stdout" );
print ( execOutput );
You may have noticed that when we use the backtick or $EXEC() then the output of
the executed command is not printed—but instead ends up as the return value of
the function. This is to prevent the printed output of executed commands from cor‐
rupting the output of the main script.
Nashorn provides two other special variables that can help the programmer to work
with the output of commands that are executed from within a script: $OUT and $ERR .
These are used to capture the output and any error messages from a command that
is executed from within a script. For example:
$EXEC ( "echo Print this on stdout" );
// Code that doesn't change stdout
var saveOut = $OUT ;
print ( "- - - - - - -" );
print ( saveOut );
The contents of $OUT and $ERR persist until they are overwritten by subsequent code
in the main script that can also affect the values held there (such as another com‐
mand execution).
Inline documents
JavaScript, like Java, does not support strings where the opening quote is on one line
and the closing quote on another (known as multiline strings ). However, Nashorn in
scripting mode supports this as an extension. This feature is also known as an inline
document or a heredoc and is a common feature of scripting languages.
To use a heredoc, use the syntax <<END_TOKEN to indicate that the heredoc starts on
the next line. Then, everything until the end token (which can be any string, but is
usually all capitals—strings like END , END_DOC , END_STR , EOF , and EOSTR are all quite
common) is part of the multiline string. After the end token, the script resumes as
normal. Let's look at an example:
var hw = "Hello World!" ;
var output = << EOSTR ;
This is a multiline string
Search WWH ::

Custom Search