sumana
sumana

Reputation: 149

Read multiple columns in perl using while loop

I am stuck in a problem in Perl.

I want to read multiple columns in 1 line using while loop.

I know I can achieve this using shell script like below

cat file.txt|while read field1 field2 field3 field4
do
statement1
statement2
done

The same thing I want in Perl but don't understand how to get this.

Please help me.

Thanks in advance, Sumana

Upvotes: 0

Views: 1203

Answers (2)

Vijay
Vijay

Reputation: 67211

use

perl -F -ane '....' your file

-F flag will store each field in an array @F.so u can use $F[0] for the first field. for example:

perl -F -ane 'print $F[0]' your file

will print the first field of every line

if you are concerned about performance:

perl -lne "my($f,$s,$t)=split;print 'first='.$f.' second='.$s.' third='.$t" your_file

for a big example :also check this

Upvotes: 2

Maurice Reeves
Maurice Reeves

Reputation: 1583

In a loop, you can do this:

#!/usr/bin/perl -w
use strict;

my $file = "MYFILE";
open (my $fh, '<', $file) or die "Can't open $file for read: $!";
my @lines;
while (<$fh>) {
    my ($field1, $field2, $field3) = split;
}
close $fh or die "Cannot close $file: $!";

In the loop, Perl will assign $_ the next line of the file, and with no args, split will split that variable on white space.

Upvotes: 2

Related Questions