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

Is there a way to assign a string across lines, like the multiline print ..

print <<END; sometext more END

Probably really obvious but I had some trouble finding out ...

Replies are listed 'Best First'.
Re: assign a string using multiline format
by Taulmarill (Deacon) on Aug 26, 2005 at 11:57 UTC
    i'm not shure i understand the question. are you asking for something like this?
    # one method my $foo = "sometext\nmore\n"; print $foo; # another method $foo = <<END; sometext more END print $foo;
      I was looking for the second. I didn't know you could assign with the << operator just like that. cheers.
Re: assign a string using multiline format
by punkish (Priest) on Aug 26, 2005 at 12:20 UTC
    This idiom is called the HEREDOC. Think of

    <<END; sometext more END
    being equivalent to "$var" where $var contains everything between the first line and the last line.

    It is interpolated, so any vars inside the HEREDOC is also expanded. So

    $foo = 'danmcb'; print <<END; $foo was here and here END # will print danmcb was here and here

    Most wherever you can use $var, you can usually use the HEREDOC. For example

    my $text = $cgi->param('text') || <<END; some text passed via the cgi END

    works very well. Keep in mind, the trailing END has to be flush with the left most column.

    --

    when small people start casting long shadows, it is time to go to bed
      ... It is interpolated, so any vars inside the HEREDOC is also expanded

      it doesn't have to be interpolated, see the following...

      print <<'END'; $foo was here and here END # will print $foo was here and here
      ---
      my name's not Keith, and I'm not reasonable.
        why will punkish' HEREDOC interpolate while heith's won't? I don't see the difference ...?
Re: assign a string using multiline format
by chibiryuu (Beadle) on Aug 26, 2005 at 15:02 UTC
    Here-docs are just a convenient way of writing long strings, so (for example)
    my_function(<<END, <<END . <<END); a END b END c END
    is equivalent to
    my_function("a\n", "b\n" . "c\n");
    You can of course use different names, i.e.
    my_function(<<A, <<B . <<C); a A b B c C
    (well, that's not really sensible...)

    Note that the here-docs must be in order, and start at the end of the line, i.e.

    printf <<'END', 1, 2, %d %d %d %d END 3, 4;
    prints 1 2 3 4.
Re: assign a string using multiline format
by chester (Hermit) on Aug 26, 2005 at 13:57 UTC
    You don't even need a heredoc in Perl to do this. But this is some mightily ugly code. (Then again, so is the heredoc version.)

    use strict; use warnings; my $string = "This is a test..."; print $string;