http://qs1969.pair.com?node_id=62552

ep has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to write some perl to read a file and pass the contents of that file line by line to another program and I am not getting anywhere! I want to pass the file as an argument to the perl program, read it and pass the contents line by line to another program...anyone? What can I say...I'm a rookie! -ep

Replies are listed 'Best First'.
Re: Reading a file
by danger (Priest) on Mar 07, 2001 at 00:01 UTC

    It really depends on what you mean by passing each line to another program: 1)Do you mean, call another program with each line as the arguments? or 2) Do you mean, pipe each line to another program's standard input? (or do you mean something altogether different?)

    # 1 #!/usr/bin/perl -w use strict; my $other_program = 'echo'; while(<>){ chomp; system($other_program, $_); } __END__ # 2 #!/usr/bin/perl -w use strict; my $other_program = 'tr [a-z] [A-Z]'; open(OTHER, "|$other_program") || die "Kant: $!"; while(<>){ print OTHER $_; } close OTHER; __END__
      Thanks for everyone's help...I'm where I need to be. There were some questions about what I'm wanting to with the data from the file. I would like to take each record of the file (one at a time) and pass that record as an argument to another perl script, shell script, etc. that performs data extraction based on the argument being passed in (i.e. zip code). Hope this clears up any of the confusion! Thanks- ep
(redmist) Re: Reading a file
by redmist (Deacon) on Mar 06, 2001 at 23:36 UTC

    Try this:

    #!/usr/bin/perl -w use strict; open (FILE, "file.txt") or die "arrrrgh...$!\n"; while (<FILE>) { print; # pass to program here } close(FILE);
    The reason you can do this is because while will read the file handle one line at a time. I am wondering what you mean by "passing it to another program." Could you just use a subroutine, or are you talking about a seperate utility?

    redmist
    Silicon Cowboy
      Maybe:
      open OUT,'|program' or die $!; open IN,'file.txt' or die $!; #if you don't need to process each line...I don't see why not printing + all the lines at once like: print OUT <IN>; #but if you must print one line at a time: while(<IN>){ #do whatever you want with the line. print OUT $_; } close OUT; close IN;
Re: Reading a file
by ep (Initiate) on Mar 07, 2001 at 22:46 UTC
    Thanks for everyone's help...I'm where I need to be. There were some questions about what I'm wanting to with the data from the file. I would like to take each record of the file (one at a time) and pass that record as an argument to another perl script, shell script, etc. that performs data extraction based on the argument being passed in (i.e. zip code). Hope this clears up any fo the confusion! Thanks- ep