Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

'here-document is a very handy Perl operator that allows to easily define multiline strings. Unfortunately, most of the times, the inclusion of a here-document string breaks the indentation level of the source code like in this example:

  while ( $something )
  {
    if ( $anything )
    {
      print <<EOF;
there goes the nicely formatted source code
because of this here-document
string
EOF
 
      #-- continue with the script
      $something = 0;

If you indent the here-document to align it with the source code, the resulting strings will have the extra spaces when you use them (something that probably isnot what you want). In order to align the here-document string with the source code and get rid of the extra leading spaces you can use the s/// operator, like the example below:

  while ( $something )
  {
    if ( $anything )
    {
      ($here = <<EOF) =~ s/^[^\S\n]+//gm;
      this multiline string
      looks nicely aligned
      with the source code
      and does not have leading whitespaces
EOF
      print $here;
 
      #-- continue with the script
      $something = 0;