Broad Network


Line Oriented Operator and Here-doc

Foreword: In this tutorial, I talk about the <<EOF operator.

By: Chrysanthus Date Published: 21 Oct 2015

Introduction

In this tutorial, I talk about the <<EOF operator. The complete operator delimits a string, giving the string special characteristics. A string is a series of characters.

Pre-Knowledge
This series is part of the volume, Perl Course. At the bottom of this page you will find links to the different series you should have read before coming here.

Double Quoted String
An example of a double quoted string literal is,

    "I like what I am seeing"

The double quote used at the start and end of the string is that of the text editor and not of the word processor. That of the word processor may result in an error message when the Perl code is run.

A double quoted string can be assigned to a variable as in the following code, which you should read and try.

use strict;
    
    my $var = "I like what I am seeing.";
    print $var;

Here-doc
Assume that you are typing in a text editor. If you want more than one consecutive spaces, you press the keyboard spacebar the corresponding number of times. If you want a newline, you press the Enter key. If you want a number of consecutive newlines, you press the Enter key the corresponding number of times. The result is an overall formatting with spaces and newlines.

Perl can send this overall formatting to the console or a text editor file, but on condition that you use the here-doc syntax (operator - see below). This would also send the overall formatting to the web page at the browser, but the web page would not display consecutives spaces and it would not display newlines. This is because the web page needs but a number of “&nbsp;” for consecutive spaces and <br> for a new line.

The above overall formatting can be seen in its entirety (all text) in the text editor page or the console.

Consider the following script

use strict;

    my $str = <<EOF;
    some spaces    yes  space
a line and yes a line
    another line and         spaces
EOF

    print $str;

The here-doc syntax begins with <<. This is followed by an identifier without $ and without space. You then have a semicolon, after which you press the Enter Key. Then you type the string content giving any number of consecutives spaces you want and just pressing the Enter key at the end of each line. The last line of the syntax, is the same identifier, and should be typed at the beginning of the last line. Immediately after that you type a semicolon and then you press the Enter key (no space before pressing the Enter key). So, the heredoc string has an opening identifier and a closing identifier, which are the same, e.g. EOF above.  You can choose any name you want for the identifier. The here-doc string above is assigned to the variable, $str. This variable is printed to the console. Read and try the above code, if you have not already done so.

Escaped Sequences
Escaped Sequences or Escaped Characters are special characters. A character here actually consists of two characters with the first one being the backslash. Common escaped sequences and their meanings are:

        Sequence     Note  Description
        \t                  tab               (HT, TAB)
        \n                  newline           (NL)
        \r                  return            (CR)
        \f                  form feed         (FF)
        \b                  backspace         (BS)
        \a                  alarm (bell)      (BEL)
        \e                  escape            (ESC)
        \c[                 control char      (example: chr(27))

Double Quoted Strings and Here-doc with Escaped Characters
An escaped character in a double quoted string has its effect at the output. For example, \t would produce a horizontal tab (indentation); \n would send the text on its right to the next line; \v would produce a vertical tab. Watch out for single and double quotes (see below). Try the following code:

use strict;

    my $var = "This is the first line.\nThis is the second line with \" a double quote.\n\tStart the third line with horizontal tab.";

    print $var;

Note: in a string delimited by double quotes, if you want a double quote within the string, you have to escape it with a backslash, otherwise there will be conflict between the double quote and the delimiters and the script will not run and it will issue an error message. However, with here-doc (as above), you type the double quote without escaping (you also type the single quote without escaping).

Read and try the following code for a here-doc example:

use strict;

    my $str = <<EOF;
    some spaces    yes  space\na line, " yes a line with double quote\n\tanother line  \$    with spaces and escaped characters
EOF

    print $str;

Single or Double Quote within a Double Quoted String
You do not have to escape a single quote while typing it within a double quoted string. A single quote typed within a double quoted string does not produce any delimiting conflict. To have a double quote within a double quoted string, you have to escape it to prevent delimiting conflict. However, with here-doc (as above), you type a double quote without escaping (you also type a single quote without escaping).

Variable
A variable within a double quoted string or here-doc string (as above), is expanded; this means that the value of the variable is obtained at the output; the value also replaces the variable in the string when the script runs. Read and try the following code:

use strict;

    my $var = "music";
    
    my $str1 = "I like $var; it makes me feel good.";
    print $str1, "\n";

    my $str2 = <<EOF;
        You should like $var; it is good.
EOF

    print $str2, "\n";

Single Quoted String and Here-doc

Now "EOF" or EOF have the same double quoted string effect. If you want single quoted string effect, use 'EOF'.

An example of a single quoted string literal is,

    'I like what I am seeing.'

The single quote used at the start and end of the string is that of the text editor and not of the word processor.

A single quoted string can be assigned to a variable as in the following code, which you should try.

use strict;
    
    my $var = 'I like what I am seeing.';
    print $var;


Try the following here-doc example for single quotes:

use strict;

    my $str = <<'EOF';
    some spaces    yes  space
a line and yes a line
    another line and         spaces
EOF

    print $str;

The spaces and lines have been maintained at the output.

Single Quoted Strings and Here-doc with Escaped Characters
With the exception of \\ and \', escape characters have no effect within a single quoted string. Try the following code:

use strict;

    my $var = 'This is the first line \\ with a backslash.\nThis is supposed to be the second line with \' a single quote.\n\tShould have started the third line with horizontal tab.';
    print $var;

At the output only the backslash and single quoted escaped characters had their effects. The rest of the escaped characters were printed as they were typed and they had no effect. Note: in a string delimited by single quotes, if you want a single quote within the string, you have to escape it with a backslash, otherwise there will be conflict with the delimiters and the script will not run and it will issue an error message. However, with a single quote here-doc, you can type the single quote (or double quote) directly.

Read and try the following code for a here-doc example:

use strict;

    my $str = <<'EOF';
    some spaces    yes  space\na line, ' yes a supposed line with single quote\n\tanother supposed line  \$    with spaces and escaped characters
EOF

    print $str;

All the escaped sequences were printed the way they were typed.

Variable and Single Quote Here-doc
A variable within a single quoted string or single quote here-doc is not expanded; this means that the value of the variable is not displayed at the output: the value of the variable does not replace the variable when the script runs. Read and try the following code:

use strict;

    my $var = 'music';
    
    my $str1 = 'I like $var; it makes me feel good.';
    print $str1, "\n";

    my $str2 = <<'EOF';
        You should like, $var; it is good.
EOF

    print $str2, "\n";

The variables have not been expanded.

Special Use of Single Quote Here-doc
The construct is ideal for embedding Perl code or other large blocks of text without the need for escaping.

Backtick Here-doc

The content of the backtick here-doc is the same as the content of the backtick quotes. The content is a system command. The following code creates a directory:

use strict;

my $ret = <<`EOF`;
        mkdir c:\dirA;
EOF

    print $ret;

The return value ($ret) is the feedback message of the operating system command.

That is it for this tutorial.

Chrys

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

Comments

Become the Writer's Fan
Send the Writer a Message