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

Greetings Fellow Monks,

I am trying to pipe the contents of a text file into a perl script. I need be able to call the script similarly to the following:
script.pl < file.txt
My script would then need to capture the contents of file.txt into an array. The following code does not accomplish this:
#!/usr/local/bin/perl -w use strict; my $line; foreach $line (@ARGV) { print "The line is: $line\n"; }

I would be extremely grateful if someone could someone give me some insight on how to accomplish this.

Thanks!

smack
“There are no cats in America, and the streets are paved with cheese.” -Fievel Mousekewitz

Replies are listed 'Best First'.
Re: Pipe File contents into Perl Script
by kyle (Abbot) on Sep 21, 2007 at 17:26 UTC

    To put the file into an array:

    my @file_lines = <>;

    To read it line by line:

    while ( my $line = <> ) { print "The line is: $line"; push @file_lines, $line; }

    You might also want to look at chomp, if you don't want line endings on your lines.

      This worked, Thanks!

      “There are no cats in America, and the streets are paved with cheese.” -Fievel Mousekewitz
        kyle@x:~$ cat perlmonks.pl #!/usr/bin/perl use strict; use warnings; my @file_lines; while ( my $line = <> ) { print "The line is: $line"; push @file_lines, $line; } kyle@x:~$ cat file.txt line one line two line three kyle@x:~$ perl perlmonks.pl < file.txt The line is: line one The line is: line two The line is: line three

        Show us the code that's not working, and maybe we can help.

        A reply falls below the community's threshold of quality. You may see it by logging in.