Chinaunix首页 | 论坛 | 博客
  • 博客访问: 773473
  • 博文数量: 180
  • 博客积分: 4447
  • 博客等级: 上校
  • 技术积分: 1582
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-03 14:51
文章分类

全部博文(180)

文章存档

2014年(6)

2013年(8)

2011年(125)

2009年(35)

2008年(1)

2007年(5)

分类: LINUX

2011-01-06 13:37:39

Here document
From Wikipedia, the free encyclopedia
Jump to: navigation, search

A here document (also called a here-document, a heredoc, a hereis, a here-string or a here-script) is a way of specifying a in including all the Unix shells (, , , and ) and in programming or scripting languages such as , , , and . It preserves the line breaks and other whitespace (including indentation) in the text. Some languages allow and inside the string.

The general syntax is << followed by a , followed, starting on the next line, by the text to be quoted, and then closed by the same identifier on its own line. Under the Unix shells, here documents are generally used as a way of providing input to commands.

Contents[hide]
[edit] Specific implementations

The following sections provide examples of specific implementations in different programming languages and environments. Most of these use syntax identical or substantially similar to the general syntax specified above, although some environments provide similar functionality but with different conventions and under different names.

[edit] Command-line shells [edit] Unix Shells

In the following example, text is passed to the using a here document.

$ tr a-z A-Z <<END_TEXT
> one two three
> uno dos tres
> END_TEXT
ONE TWO THREE
UNO DOS TRES

END_TEXT was used as the delimiting identifier. It specified the start and end of the here document. ONE TWO THREE and UNO DOS TRES are outputs from tr after execution.

Appending a minus sign to the << has the effect that leading tabs are ignored. This allows indenting here documents in shell scripts without changing their value. (Note that you will probably need to type CTRL-V, TAB to actually enter a TAB character on the command line. Tab emulated here with spaces; don't copy and paste.)

$ tr a-z A-Z <<-END_TEXT
> one two three
> uno dos tres
> END_TEXT
ONE TWO THREE
UNO DOS TRES

By default variables and also commands in backticks are evaluated:

$ cat << EOF
> Working dir $PWD
> EOF
Working dir /home/user

This can be disabled by quoting any part of the label. For example by setting it in single or double quotes:

$ cat << "EOF"
> Working dir $PWD
> EOF
Working dir $PWD
[edit] Windows PowerShell

In , here documents are referred to as here-strings. A here-string is a string which starts with an open delimiter (@" or @') and ends with a close delimiter ("@ or '@) on a line by itself, which terminates the string. All characters between the open and close delimiter are considered the string literal. Using a here-string with double quotes allows , using single quotes doesn't. Variable interpolation occurs with simple variables (e.g. $x but NOT $x.y or $x[0]). You can execute a set of statements by putting them in $() (e.g. $($x.y) or $(Get-Process | Out-String)).

In the following PowerShell code, text is passed to a function using a here-string. The function ConvertTo-UpperCase is defined as follows:

PS> function ConvertTo-UpperCase($string) { $string.ToUpper() }
PS> ConvertTo-UpperCase @'
>> one two three
>> eins zwei drei
>> '@
>>
ONE TWO THREE
EINS ZWEI DREI

Here is an example that demonstrates variable interpolation and statement execution using a here-string with double quotes:

$doc, $marty = 'Dr. Emmett Brown', 'Marty McFly'
$time = [DateTime]'Friday, October 25, 1985 8:00:00 AM'
$diff = New-TimeSpan -Minutes 25
@"
$doc : Are those my clocks I hear?
$marty : Yeah! Uh, it's $($time.Hour) o'clock!
$doc : Perfect! My experiment worked! They're all exactly $($diff.Minutes) minutes slow.
$marty : Wait a minute. Wait a minute. Doc... Are you telling me that it's $(($time + $diff).ToShortTimeString())?
$doc : Precisely.
$marty : Damn! I'm late for school!
"@

Output:

Dr. Emmett Brown : Are those my clocks I hear?
Marty McFly : Yeah! Uh, it's 8 o'clock!
Dr. Emmett Brown : Perfect! My experiment worked! They're all exactly 25 minutes slow.
Marty McFly : Wait a minute. Wait a minute. Doc... Are you telling me that it's 08:25?
Dr. Emmett Brown : Precisely.
Marty McFly : Damn! I'm late for school!

Using a here-string with single quotes instead, the output would look like this:

$doc : Are those my clocks I hear?
$marty : Yeah! Uh, it's $($time.Hour) o'clock!
$doc : Perfect! My experiment worked! They're all exactly $($diff.Minutes) minutes slow.
$marty : Wait a minute. Wait a minute. Doc... Are you telling me that it's $(($time + $diff).ToShortTimeString())?
$doc : Precisely.
$marty : Damn! I'm late for school!
[edit] Programming languages [edit] D

Since version 2.0, has support for delimiter strings using the 'q' prefix character. These strings begin and end with a delimiter character (any of () <> {} or []), or an identifier immediately followed by a newline.

The following D code shows 2 examples using delimiter characters and an identifier.

int main() {
string list = q"[1. Item One
2. Item Two
3. Item Three]"
;
writef( list );
}

Using an identifier.

int main() {
string list = q"IDENT
1. Item One
2. Item Two
3. Item Three
IDENT"
;
writef( list );
}
[edit] PHP

In PHP, here documents are referred to as heredocs.



$name = "Joe Smith";
$occupation = "Programmer";
echo <<
This is a heredoc section.
For more information talk to $name, your local $occupation.

Thanks!

EOF
;

$toprint = <<
Hey $name! You can actually assign the heredoc section to a variable!

EOF
;
echo strtolower($toprint);

?>

Outputs

This is a heredoc section.
For more information talk to Joe Smith, your local Programmer.

Thanks!

hey joe smith! you can actually assign the heredoc section to a variable!

The line containing the closing identifier must not contain any other characters, except an optional ending semicolon. Otherwise, it will not be considered to be a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found, a parse error will result with the line number being at the end of the script.[1] As of PHP 5.3.0 HereDoc in PHP can be initiated with double quotes (not unlike Python which uses triple quotes).

[edit] Perl

In Perl there are several different ways to invoke here docs[2]. Using double quotes around the tag allows , using single quotes doesn't and using the tag without either behaves like double quotes. Using backticks as the delimiter runs the contents of the heredoc as a shell script. It is necessary to make sure that the end tag is at the beginning of the line or the tag will not be recognized by the interpreter.

Here is an example with double quotes:

my $sender = "Buffy the Vampire Slayer";
my $recipient = "Spike";

print <<"END";

Dear $recipient,

I wish you to leave Sunnydale and never return.

Not Quite Love,
$sender

END

Output:

Dear Spike,

I wish you to leave Sunnydale and never return.

Not Quite Love,
Buffy the Vampire Slayer

Here is an example with single quotes:

print <<'END';
Dear $recipient,

I wish you to leave Sunnydale and never return.

Not Quite Love,
$sender
END

Output:

Dear $recipient,

I wish you to leave Sunnydale and never return.

Not Quite Love,
$sender

And an example with backticks (may not be portable):

my $shell_script_stdout = <<`END`;
echo foo
echo bar
END
[edit] Python

supports heredocs delimited by single or double quotes repeated three times (i.e. ''' or """).

A simple example with variable interpolation that yields the same result as the first Perl example above, is:

print """Dear %(recipient)s,

I wish you to leave Sunnydale and never return.

Not Quite Love,
%(sender)s
"""
% {'sender': 'Buffy the Vampire Slayer', 'recipient': 'Spike'}

The Template class described in PEP 292 (Simpler String Substitutions) provides similar functionality for variable interpolation and may be used in combination with the Python triple-quotes syntax.

[edit] Ruby

The following Ruby code displays a grocery list by using a here document.

puts <<-GROCERY_LIST
Grocery list
------------
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*

* Organic
GROCERY_LIST

The result:

$ ruby grocery-list.rb
Grocery list
------------
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*

* Organic

Writing to a file with a here document involves a profusion of chevron ('<') symbols:

File::open("grocery-list", "w") do |f|
f << <<-GROCERY_LIST
Grocery list
------------
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*

* Organic
GROCERY_LIST
end

Ruby also allows for the delimiting identifier not to start on the first column of a line, if the start of the here document is marked with the slightly different starter "<<-". Besides, Ruby treats here documents as a double-quoted string, and as such, it is possible to use the #{} construct to interpolate code. The following example illustrates both of these features :

now = Time.now
puts <<-EOF
It's #{now.hour} o'clock John, where are your kids?
EOF

Ruby also allows for starting multiple here documents in one line:

puts <<BEGIN + "<--- middle --->\n" + <<END
This is the beginning:
BEGIN
And now it is over!
END

# this equals this expression:
puts "This is the beginning:\n<--- middle --->\nAnd now it is over!"
[edit] Tcl

has no special syntax for heredocs, because the ordinary string syntaxes already allow embedded newlines and preserve indentation. Brace-delimited strings have no substitution (interpolation):

puts {
Grocery list
------------
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*

* Organic
}

Quote-delimited strings are substituted at runtime:

set sender "Buffy the Vampire Slayer"
set recipient "Spike"

puts "
Dear $recipient,

I wish you to leave Sunnydale and never return.

Not Quite Love,
$sender
"

In brace-delimited strings, there is the restriction that they must be balanced with respect to unescaped braces. In quote-delimited strings, braces can be unbalanced but backslashes, dollar signs, and left brackets all trigger substitution, and the first unescaped double quote terminates the string.

A point to note is that both the above strings have a newline as first and last character, since that is what comes immediately after and before respectively the delimiters. string trim can be used to remove these if they are unwanted:

puts [string trim "
Dear $recipient,

I wish you to leave Sunnydale and never return.

Not Quite Love,
$sender
"
\n]

Similarly, string map can be used to effectively set up variant syntaxes, e.g. undoing a certain indentation or introducing nonstandard escape sequences to achieve unbalanced braces.

[edit] See also
  • for information about tr(1)
  • for information about pipes
[edit] References
  1. ^
  2. ^
Namespaces
Variants
Actions
阅读(2227) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~