Why do I get this syntax error in my code generating program?
I want to generate some lines of Perl code by using file handling in Perl, for example:
open(FILEHANDLE, ">ex.pl") or die "cannot open file for reading: $!";
print FILEHANDLE "use LWP::UserAgent;"
....
.... some code is here
....
print FILEHANDLE "my \$ua = new LWP::UserAgent(agent => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.5) Gecko/20060719 Firefox/1.5.0.5');"
But when I compile the generator code (not the generated) I get this error:
syntax error at F:\test\sys.pl line 14, near "print"
Execution of F:\test\sys.pl aborted due to compilation errors.
What am I 开发者_如何学Cgoing to do?
You missed the closing ' " '
(double quote) at the end of the last print's string (before semicolon).
Should be:
print FILEHANDLE "my \$ua = new LWP::UserAgent(agent => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.5) Gecko/20060719 Firefox/1.5.0.5')";
... Firefox/1.5.0.5')"; # To show end of that line without scrolling
Also, couple of minor notes:
Please consider using 3-argument form of
open()
, not 2-argument; as well as lexical filehandles:open(my $fh, '>', "out.txt") or die "Error opening for writing: $!"; print $fh "stuff\n";
You don't have a
close()
of the filehandle at the end - I assume just because you gave incomplete code.
You're missing a semicolon on the end of this line:
print FILEHANDLE "use LWP::UserAgent;"
This is how you'd write it in modern Perl:
use autodie qw(:all);
{
open my $handle, '>', 'ex.pl';
print {$handle} <<'PERL_SOURCE';
use LWP::UserAgent;
…
# ↓ no variable quoting necessary thanks to here-document
my $ua = LWP::UserAgent->new(agent => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.5) Gecko/20060719 Firefox/1.5.0.5');
…
PERL_SOURCE
}
As Ether hinted at in comments at the top, it's almost never necessary to write out dynamically generated code into a file. eval
and Moose::Meta::*
exist for a reason.
精彩评论