0

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

4
  • What do you want to split the line from the file on? Commented Dec 30, 2012 at 4:46
  • Yes, there might be many fields in file but I want to extract only n number of fields like shown above and then I will use these variables below. I know array is alternative but I wanted to check if there is any easier method available like shell provides here. Commented Dec 30, 2012 at 4:50
  • 1
    @Sumana, that doesn't extract n fields. What happens is all fields after the 4th get slurped into your "field4" variable. Maruice's answer behaves exactly the same. To discard the remaining, you need an additional _ in bash or undef in the perl version. Commented Dec 30, 2012 at 6:14
  • @jordanm - good point. I was working off the assumption of three fields. Feel free to edit the script to reflect this reality if you want, or I can later on. Commented Dec 30, 2012 at 6:20

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes. It solved my purpose. Thank you very much Maurice for your kind help.
My pleasure! Best of luck, and when you have a chance, if you haven't already, please mark my answer as accepted. Cheers!
2

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

1 Comment

I know array can solve this purpose but that's a bit lengthy and it uses memory also to assign many unwanted values so I wanted to check if Perl also provide any easier method like shell as in my example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.