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

let's say I'm reading the following line form a text file
Hello\nWorld

which is equivalent to:
my $Message = 'Hello\nWorld';
I want to print this string and I want PERL to interpret the \n as a line break.

print($Message);
gives
Hello\nWorld
which is what I would expect

print("$Message");
also gives
Hello\nWorld
I was hopping that "" would cause the string to be interpreted but no...?

I tried
print(eval{"$Message"});
same result

Of-course I could split my string and print each section on a newline myself but it should be possible to have perl interpret this string.

Thanks for your help.

Replies are listed 'Best First'.
Re: Line break interpretation
by davorg (Chancellor) on Oct 19, 2006 at 15:35 UTC

    String eval does the trick.

    my $m = 'Hello\nWorld'; print eval "qq($m)";
    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      That solved my issue, thanks a lot.

        Be careful! If the input is untrusted, that snippet could execute arbitrary code. (Consider my $m = '); arbitrary perl command here';) Be sure to place big red arrows in your comments.

        String::Interpolate might be safer.

      String eval does the trick.

      In addition to the other solutions that avoid string eval and its inherent risks, there's YAML::Syck::Load although that's probably an overkill:

      print Load '--- "Hello\nWorld\n"';
Re: Line break interpretation
by Molt (Chaplain) on Oct 19, 2006 at 17:06 UTC
    Another approach which may be suitable if it's only line-breaks you're interested in may be to use a substitution.
    #!/usr/bin/perl use strict; use warnings; my $msg = 'Hello\nWorld'; print "Msg was $msg\n"; $msg =~ s/\\n/\n/g; print "Msg is $msg\n";
Re: Line break interpretation
by prasadbabu (Prior) on Oct 19, 2006 at 15:21 UTC

      You're misunderstanding the question. The string is being read from a file. Try working with this:

      #!/usr/bin/perl use strict; use warnings; my $message = <DATA>; # ... some code goes here print $message; __END__ Hello\nWorld

      Putting the string in single quotes simulates the action of reading the data from a file.

      --
      <http://dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg