Newbph Newbph - 1 year ago 66
Perl Question

foreach x ( cat file ) in perl?

Trying to run the code:

foreach x ( `cat file`)
echo $x

Expected output when ran on unix:


When ran on perl script:

1 2 3 4 5

Please advise on how to achieve output like in unix in perl?

Answer Source

Your code is not even in Perl

foreach x ( `cat file`)
echo $x
  1. There's no echo or end command in Perl.
  2. Why are you using system's cat command? You should use pure Perl for such trivial tasks.

I assume you are trying to loop over contents of a file and then print each line.

In Perl you can do it using below:

#always use the below 2 lines in your Perl program
use strict;
use warnings;

my $filename = '/path/to/file';
#open file in read mode
open (my $fh, "<", $filename) or die "Could not open file $!";
#use while to iterate over each line
while my $line (<$fh>){
    print $line;

Or you could take file's content in an array then loop over it

my @lines = <$fh>;
foreach my $line (@lines){
    print $line;