Home > Software engineering >  Perl command executing good when run on command line but not working in the Perl script
Perl command executing good when run on command line but not working in the Perl script

Time:10-30

Below is the code I'm trying to execute. I have mentioned the line 266 in the code. I have added that code to remove the blank lines in the log file. I'm not sure whether we can run the perl command inside a Perl script. Is there another way that I can run this so that I can remove the blank lines in the log file?

Below is the error I'm getting while running through the Perl script:

syntax error at ./reportJBossErrors.pl line 266, near "n -e "
Execution of ./reportJBossErrors.pl aborted due to compilation errors.

Here is a portion of the code, showing line 266:

sub main {
    readConfiguration($config_file);
    $short_hostname = `hostname | cut -f 1 -d.`;
    chomp $short_hostname;
    getFileandInstance($short_hostname);
    $yesterday = getYesterday();
    validateEnvironment();
    $log_file = getLogFile($FMASK,$yesterday);
    perl -i -n -e "print if /\S/" $log_file; # 266 line. This is where I'm getting the compilation error
    processFile($log_file);
    $html_out = writeEmail();
    sendEmail($CONFIG{"FROMADDR"},$CONFIG{"TOADDR"},"Normal",
    "JBOSS",$short_hostname,$log_file,$CONFIG{ENVTYPE},$html_out);
}

CodePudding user response:

You can not call the perl command inside a Perl program as if it were a Perl builtin function. You can use system to run an external command:

my $cmd = 'perl -i -n -e "print if /\S/"';
system "$cmd $log_file";

You need to be careful of quoting. Since you have a file name/path in the Perl variable $logfile, which you want to interpolate, that can go inside double quotes. Since you do not want to interpolate \S, that should go in single quotes.

CodePudding user response:

You cannot invoke the perl executable inside a Perl program as if it were a Perl builtin function. Instead, use the list form of system to run an external command. Don't forget to check if the command succeeded:

my @cmd = (perl => '-i', '-n', '-e', 'print if /\S/', $log_file);

system(@cmd) == 0
    or die "system @cmd failed: $?";

In general, I would recommend using the full path to perl rather than relying on $PATH.

Also, if you need to keep track of status etc, use Capture::Tiny to get both STDOUT and STDERR of the command you are running so that you can log error information.

  •  Tags:  
  • perl
  • Related