heredoc

Almost all scripting languages support heredoc, include bash, perl, python, ruby, php and tcl, and more.

Bash

<< and delimiting identifer like EOF.

cat <<EOF
working dir is $PWD
working dir is `pwd`
EOF

Output:

working dir is /home/user
working dir is /home/user

By default, variables and commands in backticks are evaluated. This can disabledby setting the label in the command line in single or double quotes:

cat <<"EOF"
working dir is $PWD
working dir is `pwd`
EOF
 
cat <<'EOF'
working dir is $PWD
working dir is `pwd`
EOF

Output:

working dir is $PWD
working dir is `pwd`
working dir is $PWD
working dir is `pwd`

Perl

Like Bash, and using double quotes around the tag allows variables to be interpolated, using single quotes doesn't and using the tag without either behaves like double quotes.

my var="World"
 
# without quotes
print <<EOF;
Hello $var
EOF
 
# double quotes
print <<"EOF";
Hello $var
EOF
 
#single qutoes:
print <<EOF;
Hello $var
EOF

The output:

Hello World
Hello World
Hello $var

Python

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

var = 'World'
 
print("""
Hello %(var)s
""" % locals())
 
print('''
Hello %(var)s
''' % locals())

Output:

Hello World
Hello World

Ruby

Ruby's grammer is from Bash and Perl.

now = Time.now
 
puts <<EOF
Hello #{now.hour}
EOF
 
puts <<"EOF"
Hello #{now.hour}
EOF
 
puts <<'EOF'
Hello #{now.hour}
EOF

Output:

Hello World
Hello World
Hello #{now.hour}

PHP

<?php
var = World;
 
// heredoc
echo <<<EOF
Hello $var
EOF;
 
// nowdoc, need php 5.3
echo <<<'EOF'
Hello $var
EOF;
?>

Output:

Hello World
Hello $var

Tcl

Tcl's ordinary string syntaxes already allow embedded newlines and preserve indentation.

set var "World"
 
puts "
Hello $var
"
 
puts {
Hello $var
}

Output:

Hello World
Hello $var

References

http://en.wikipedia.org/wiki/Heredoc
http://php.net/manual/en/language.types.string.php

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">