Документация
HTML CSS PHP PERL другое

Section 4.12.  Heredoc Quoters

 
Previous
Table of Contents
Next

4.12. Heredoc Quoters

When introducing a heredoc, quote the terminator.

Notice that all the heredoc examples in the previous guidelines used either single or double quotes after the <<. Single-quoting the marker forces the heredoc to not interpolate variables. That is, it acts just like a single-quoted string:


    Readonly my $GRIPE => <<'END_GRIPE';
    $minimal for maximal work
    END_GRIPE

    print $GRIPE;    
# Prints: $minimal for maximal work

Double-quoting the marker ensures that the heredoc string is interpolated, just like a double-quoted string:


    Readonly my $GRIPE => <<"END_GRIPE";
    $minimal for maximal work
    END_GRIPE

    print $GRIPE;    
# Prints: 4.99 an hour for maximal work

Most people aren't sure what the default interpolation behaviour is if you don't use any quotes on the marker:

    Readonly my $GRIPE => <<END_GRIPE;
    $minimal for maximal work
    END_GRIPE

    print $GRIPE;    # ???

Do you know? Are you sure? And even if you are sure you know, are you sure that your colleagues all know?

And that's the whole point. Heredocs aren't used as frequently as other types of strings, so their default interpolation behaviour isn't as familiar to most Perl programmers. Adding the explicit quotes around the heredoc marker takes almost no extra effort, but it relieves every reader of the considerable extra effort of having to remember the default behaviour[*]. Or, more commonly, of having to look up the default behaviour every time.

[*] Which happens to be: interpolate like a double-quoted string.

It's always best practice to say precisely what you mean, and to record as much of your intention as possible in the actual source codeeven if saying what you mean makes the code a little more verbose.

    Previous
    Table of Contents
    Next
    © 2000- NIV