0

I have a problem with the following code (Perl/Cygwin)

#!/usr/bin/perl
open FILE, ">", "filename.txt" or die $!;
print FILE "A\n";
print FILE "B\n";
print FILE "C\n";
close (FILE); 
system("xargs echo E < filename.txt");

I want it to invoke echo three times and print

E A
E B
E C

but instead it outputs

E A B C

I have tried various things with the xargs delimiter settings to no avail. Can anyone help?

paperjam
  • 8,321
  • 12
  • 53
  • 79
  • Also see http://stackoverflow.com/questions/199266/make-xargs-execute-the-command-once-for-each-line-of-input - why didn't SO search throw this up for me? SO does raise this as related though. – paperjam Nov 10 '11 at 21:59

4 Answers4

4

Try xargs -n1 echo E < filename.txt

Bill Ruppert
  • 8,956
  • 7
  • 27
  • 44
1

The 'xargs' is doing exactly what it should. Why spawn an external process to do what Perl can do? Instead, close your FILE and do:

open FILE, '<', 'filename.txt' or die $!;
while (<FILE>) {
    print "E $_";
}
JRFerguson
  • 7,426
  • 2
  • 32
  • 36
  • I want to use xargs -P to run the tasks in parallel. And I know perl can do this too. – paperjam Nov 10 '11 at 20:36
  • @paperjam: Running in parallel should have been mentioned in the OP. And I hope you want to do more than just 'echo' as many of these answers focus on, since running 'echo' in parallel is pointless. – runrig Nov 10 '11 at 21:04
  • @paperjam: Then use Bil Ruppert's suggestion and add the 'P ' argument. – JRFerguson Nov 10 '11 at 21:08
  • Sorry, I thought it was obvious that my actual script is a little more involved. Otherwise, I'd just print the output string I wanted! – paperjam Nov 10 '11 at 21:55
1

Why not use fork:

my @arr = qw(A B C);
for my $c (@arr) {
  fork and next;
  exec( echo => $c );
}

This could use some more validation, and you can get more control over how many concurrent processes you have with something like Parallel::ForkManager, and I assume you're really doing something more involved than 'echo'.

runrig
  • 6,486
  • 2
  • 27
  • 44
  • `xargs -P x` is already less characters than `Parallel::ForkManager` and the perfect tool for the jobs. – paperjam Nov 10 '11 at 21:57
  • @paperjam - less characters? You're writing to a temp file. How many characters (and how much unnecessary work) is that? – runrig Nov 14 '11 at 16:56
0
open my $file, '<', 'filename.txt' or die $!; 
while (<$file>){ 
  print "E $_"; 
}
wespiserA
  • 3,131
  • 5
  • 28
  • 36