avo has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have some code to store in variables. I decided to go for here-doc quoting of string which contains the code. However, it is interpolated which is not quite nice in my case. Is there any module I can use to do similar to here-doc quoting which doesn't interpolate the content. Herewith an example of what is happening.
my $store = <<DATA; my $interpolated_var; DATA my $store = <<DATA; my $never_defined_in_main_program_var; DATA
In other words, I would like the effect of $store = ' '. But for large multi-line text blocks. Any ideas are welcome. Thank you very much for your input.

Replies are listed 'Best First'.
Re: here-doc question
by davido (Cardinal) on Jan 17, 2009 at 07:37 UTC

    If you put the initial DATA in single quotes, interpolation goes away.

    my $store = <<'DATA'; $this_wont_be_interpolated DATA

    This is explained in better detail in perlop, under the HERE-doc section. The options for here-doc quoting are "double quote" style interpolation (default), "single quote" style non-interpolation, and back-tick style.


    Dave

      Note the side-effect that "\" ceases to be special.
      my $baz = 'interpolated'; print <<__EOI__; Double quoted or unquoted $baz foo\\bar __EOI__ print("\n"); print <<'__EOI__'; Single quoted $baz foo\\bar __EOI__
      Double quoted or unquoted interpolated foo\bar Single quoted $baz foo\\bar
Re: heredoc interpolation
by BrowserUk (Patriarch) on Jan 17, 2009 at 10:13 UTC

    Note that you can combine heredocs with other constructs. For example if you are constructing some complex sub amd don't want to backwack everything, but do want to interpolated in one or two places, then you can do something like:

    my $code = sprintf <<'EOC', $var1, $var2; sub doSomething { my( $arg1, $arg2 ) = @_; my $result; ... my $var = 2 * %d * %d; ... return $result; }

    You can even take that a stage further and use multiple heredocs in one statement.

    For example you might use one that doesn't interpolate and another that does:

    my $code = sprintf <<'EOD', $a, <<EOD2; my $var = %d; %s my $y = 123455; EOD my \$x x= 1000 * $.; EOD2 print $code; my $var = 0; my $x x= 1000 * 18; my $y = 123455;

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: heredoc interpolation
by AnomalousMonk (Archbishop) on Jan 18, 2009 at 03:31 UTC
    And, of course, plain, old single-quoted strings can contain embedded newlines, they just won't interpolate  \n newline escape sequences.
    use warnings; use strict; my $string = 'this string has five newlines '; print $string;
    Output:
    >perl t_sq_newlines_1.pl this string has five newlines