Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's an easy way to print a multi-line string without variable substitution in Perl?

Tags:

perl

I have a Perl program that reads in a bunch of data, munges it, and then outputs several different file formats. I'd like to make Perl be one of those formats (in the form of a .pm package) and allow people to use the munged data within their own Perl scripts.

Printing out the data is easy using Data::Dump::pp.

I'd also like to print some helper functions to the resulting package.

What's an easy way to print a multi-line string without variable substitution?

I'd like to be able to do:

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

But then I'd have to escape all of the $'s.

Is there a simple way to do this? Perhaps I can create an actual sub and have some magic pretty-printer print the contents? The printed code doesn't have to match the input or even be legible.

like image 331
mmccoo Avatar asked Nov 27 '22 21:11

mmccoo


2 Answers

Enclose the name of the delimiter in single quotes and interpolation will not occur.

print <<'EOL';
  sub xyz { 
    my $var = shift;
  }
EOL
like image 198
1800 INFORMATION Avatar answered Mar 30 '23 00:03

1800 INFORMATION


You could use a templating package like Template::Toolkit or Text::Template.

Or, you could roll your own primitive templating system that looks something like this:

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;
}

This looks nice and simple, but there are various traps and tricks waiting for you if you DIY. Did you notice that I failed to use quotemeta on my key names in the substituion?

I recommend that you use a time-tested templating library, like the ones I mentioned above.

like image 44
daotoad Avatar answered Mar 30 '23 00:03

daotoad