What is an easy way to print a multi-line string without changing variables in Perl?

I have a Perl program that reads a bunch of data, processes it, and then outputs several different file formats. I would like Perl to be one of these formats (as a .pm package) and allow people to use overloaded data in their own Perl scripts.

Printing data is easy with Data :: Dump :: pp .

I would also like to print some helper functions for the resulting package.

What is an easy way to print a multi-line string without changing variables?

I would like to be able to:

print <<EOL;
  sub xyz { 
    my $var = shift;
  }
EOL

But then I have to run away from all $ .s

? , - - ? .

+5
5

perl, B:: Deparse, .

+1

, .

print <<'EOL';
  sub xyz { 
    my $var = shift;
  }
EOL
+40

, Template:: Toolkit Text:: Template.

, :

my %vars = qw( foo 1 bar 2 );
Write_Code(\$vars);

sub Write_Code {
    my $vars = shift;

    my $code = <<'END';

    sub baz {
        my $foo = <%foo%>;
        my $bar = <%bar%>;

        return $foo + $bar;
    }

END

    while ( my ($key, $value) = each %$vars ) {
        $code =~ s/<%$key%>/$value/g;
    }

    return $code;
}

, , DIY. , quotemeta ?

, ​​ , .

+4

Perl:

#!/usr/bin/perl

use strict;
use warnings;

print <DATA>;
#print munged data

__DATA__
package MungedData;

use strict;
use warnings;

sub foo {
    print "foo\n";
}
+2

, :

my $mail = "Hello!

Blah blah.";

, , heredocs ( <<<EOL ).

" , ". , - " ".

Perl is actually quite rich in convenient things to make things more readable, for example. other operations with quotes. qq and q correspond to "and", and you can use any delimiter that makes sense:

my $greeting = qq/Hello there $name!
Nice to meet you/;  # Interpolation

my $url = q|http://perlmonks.org/|;     # No need to escape /

(note that the syntax coloring here is not completely strengthened)

Read perldoc perlop(find: “Quotation and query-like operators” on the page) for more information.

+2
source

All Articles