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

I'm updating one of my modules which will facilitate automating the injection of code into Perl (and Python) files (primarily inside of subs).

My question is whether there's a way to perl -c an array of perl code as a whole without executing it within a running program, where each element in the array is a line of code?

Replies are listed 'Best First'.
Re: "perl -c" an array of code in a running program
by BrowserUk (Patriarch) on Jul 21, 2015 at 23:25 UTC

    You could try wrapping the array code into a subroutine and evaling it to detect errors:

    my @code = ...; my $sub = join "\n", 'use strict;', 'use warnings;', 'sub test {', @co +de, '} 1;'; if( eval $sub != 1 ) { ## look in $@ for errors; }

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
    I'm with torvalds on this Agile (and TDD) debunked I told'em LLVM was the way to go. But did they listen!
Re: "perl -c" an array of code in a running program
by Eily (Monsignor) on Jul 21, 2015 at 23:13 UTC

    You could try to actually run perl -c on your code: my @results = map { system "echo '$_' | perl -c " } @code;. You have to escape your strings correctly though.

    Or an eval may do the trick as well: my @results = map { eval "sub { $_ }"; $@ } @code; where adding a sub block prevents the code from actually being run.

    In both those exemple you might still have code that is run, in a BEGIN block for example.