Mike Froetscher
Mike Froetscher

Reputation: 43

How to execute a command for every line in file?

open my $directory, '<', abc.txt 

chomp(my @values = <$directory>);

There is a file named abc.txt with the following contents:

abcde
abc
bckl
drfg
efgt
eghui
webnmferg

With the above lines, I am sending contents of file abc.txt into an array

Intention is to create a loop to run a command on all the lines of file abc.txt

Any suggestions for creating the loop?

Upvotes: 3

Views: 343

Answers (2)

Chankey Pathak
Chankey Pathak

Reputation: 21676

create a loop to run a command on all the lines of file abc.txt

foreach my $line (@lines){
        #assugming $cmd contains the command you want to execute
        my $output = `$cmd $line`;
        print "Executed $cmd on $line, output: $output\n";
}

Edit: As per Sebastian's feedback

my $i = 0;
while ($i <= $#lines){
        my $output = `$cmd $lines[$i]`;
        print "Executed $cmd on $lines[$i], output: $output\n";
}

OR if you are ok with destroying array then:

while (@lines){
        my $line = shift @lines;
        my $output = `$cmd $line`;
        print "Executed $cmd on $line, output: $output\n";
}

If you wanted safe code that didn't refer to the array twice, you could use splice in a list assignment.

while (my ($line) = splice(@array, 0, 1)) {
        my $output = `$cmd $line`;
        print "Executed $cmd on $line, output: $output\n";
}

Upvotes: 2

Sebastian
Sebastian

Reputation: 2550

open my $directory_fh, '<', abc.txt or die "Error $! opening abc.txt";
while (<$directory_fh>) {
    chomp; # Remove final \n if any
    print $_; # Do whatevery you want here
}
close $directory_fh;

I prefer to suffix all filehandles with _fh to make them more obvious.

while (<fh>) loops though all lines of the file.

You might need/want to remove a final \r if the file might have Windows/MS-DOS format.

Upvotes: 3

Related Questions