Tomas Kocian
Tomas Kocian

Reputation: 83

How to execute command stored in file in perl

I want to run this command but not from command line. I want to run file for example first.pl which do some other commands. For example when i run this file I want to do this:

perl -ne "print qq{$1\n} if /^\s+ (\w+)/x" file

it should be in this file. I try something like this:

my $input = "input.txt";
my @listOfFiles = `perl -ne "print qq{$1\n} if /^\s+ (\w+)/x" $input`;
print @listOfFiles;

but it print nothing. Thanks for your answers.

Upvotes: 1

Views: 705

Answers (2)

Barmar
Barmar

Reputation: 780688

There's no need to run a separate perl command, just do what you want in the main script:

open my $file, "input.txt";
my @listOfFiles;
while (<$file>) {
  if (/^\s+ (\w+)/x) {
    push @listOfFiles, $1;
  }
}
close $file;
print "@listOfFiles";

Upvotes: 2

ikegami
ikegami

Reputation: 385546

Always use use strict; use warnings;! You would have gotten

Unrecognized escape \s passed through
Unrecognized escape \w passed through
Use of uninitialized value $1 in concatenation (.) or string

As $1 is addition to the desired $input. So you need to properly escape your argument. Assuming you're not on a Windows system,

use strict;
use warnings;

use String::ShellQuote qw( shell_quote );

my $input = "input.txt";
my $cmd = shell_quote('perl', '-ne', 'print "$1\n" if /^\s+ (\w+)/x', $input);
chomp( my @listOfFiles = `$cmd` );
print "$_\n" for @listOfFiles;

Upvotes: 3

Related Questions