Search code examples
stringrakumultilinetemplate-literals

How do I create a multiline string in Raku?


In JavaScript (ES6), you can use template literals (``) to create multiline strings as shown in the following example:

const html = `
  <div>
    <p>Raku is <b>ofun</b>.</p>
  </div>
`

What's the Raku equivalent of this?


Solution

  • my constant html = '
      <div>
        <p>Raku is <b>ofun</b>.</p>
      </div>
    ';
    

    works fine in Raku.

    However, you probably want to use a so-called heredoc:

    my constant html = q:to/HTML/;
      <div>
        <p>Raku is <b>ofun</b>.</p>
      </div>
    HTML
    

    omits the first newline but is otherwise the exact equivalent. If you want to interpolate variables, you can change q to qq:

    my $lang = <Raku Rust Ruby>.pick;
    my $html = qq:to/HTML/;
      <div>
        <p>$lang is <b>ofun</b>.</p>
      </div>
    HTML
    

    For way more than you probably want to know about quoting, see Quoting Constructs