J. Linne J. Linne - 3 months ago 7
Perl Question

Using commands inside scripts for Perl?

I trying to run a perl command inside a script and here is what I got:

filenumber1.txt:

94088076164765675


The command window looks okay:

C:\Users\Guest\Documents\Prime Numbers>perl -Mntheory=:all -nE "chomp; say next_prime($_);" filenumber1.txt

94088076164765687

I am trying to do this in a script as well called primenumbers.pl and generate another file called log.txt as the output file and filenumber1.txt as the input file:

#!/usr/bin/env perl
use warnings;
use strict;
use feature 'say';
use ntheory ":all";

# open filehandle log.txt
open (my $LOG, '>>', 'log.txt');
# select new filehandle
select $LOG;

perl -Mntheory=:all -nE "chomp; say next_prime($_);" filenumber1.txt


primenumbers.pl is in the same directory as filenumbers.txt and something is wrong when I run the script and I do not know what:

C:\Users\Guest\Documents\Prime Numbers>perl primenumbers.pl

Bareword found where operator expected at primenumbers.pl line 7, near ""say next_prime($_);" filenumber1.txt"

(Missing operator before filenumber1.txt?)


syntax error at primenumbers.pl line 7, near ""say next_prime($_);" filenumber1.txt"

Execution of primenumbers.pl aborted due to compilation errors.

I tried fixing it myself, but I only made matters worse, and there were more problems to fix. Does anyone know how to help me from here please on generating the output file "log.txt" without viewing the input file "filenumber1.txt"? Thanks in advance.

Answer

The -n switch to perl just wraps the code in while (<>) { ... }, so, to get a similar effect in your own program, just add the loop yourself (untested code; may contain errors):

#!/usr/bin/env perl
use warnings;
use strict;
use feature 'say';
use ntheory ":all";

# open filehandle log.txt
open (my $LOG, '>>', 'log.txt');
# select new filehandle
select $LOG;

while (<>) {
  chomp; say next_prime($_);
}

Run this with

primenumbers.pl filenumber1.txt

and you should be set.