6

I am trying to initialize a hash like this:

use strict;

my %hash =
(
    key => <<END;
abc
def
END
    ,
    another_key => 17
);

When I run perl -cw on this code, I get the error 'syntax error at hash-initialize-test.pl line 5, near ";"'.

Is there a way to use HEREIS notation (such as <<END;) within hash initialization? If not, why not?

There are several simple workarounds, but I like to use HEREIS notation for multi-line strings because it is elegant and avoids introducing unnecessary variables.

choroba
  • 231,213
  • 25
  • 204
  • 289
David Levner
  • 341
  • 1
  • 8
  • I tried choroba's solution and it worked. Previously, I had always used a semi-colon within HEREIS notation and had never terminated the end-quote with a comma, but it makes sense in this case because the key-value pair within the hash initialization ends with a comma. Thanks! – David Levner Jan 04 '15 at 22:58
  • It is usually called a [**HEREDOC**](https://duckduckgo.com/?q=perldoc+heredoc). ( don't change the question as people searching for hereis need to be able to find the information too ) – Brad Gilbert Jan 06 '15 at 06:29

1 Answers1

9

Remove the semicolon. There is no statement end.

my %hash = ( key => <<'END',
abc
def
END
             another_key => 17,
           );
choroba
  • 231,213
  • 25
  • 204
  • 289