views:

80

answers:

3

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 going to do?

+2  A: 

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.

DVK
yes but when i put " at the end of last print i get this error again .I edit it
Eve
@Jessica: Did you put it before ':' as in the example in the answer?
DVK
@dvk:iam really sorry .
Eve
@Jessica - nothing to be sorry about,my wording was't as clear as it shoulda been (this the actual code example :)Did it work now?
DVK
Yes . Its work . Thanks a lot @DVK . Kiss you :d
Eve
@Jessica - LOL... I'm gonna have to pass on the kiss upon the threat of bodily harm from Mrs. DVK, but "accepting" this answer by clicking on a checkmark next to it and/or up-voting it by clicking on an up-arrow next to it would be very much appreciated.
DVK
+1  A: 

You're missing a semicolon on the end of this line:

print FILEHANDLE "use LWP::UserAgent;"
Phil
@Phil - original version of the question had the semicolon but not the closing quote... the one out there right now is an updated one
DVK
A: 

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.

daxim