sk215
sk215

Reputation: 111

Split using perl when tab is the delimiter between columns

Suppose the data is:

1 2 3 4 5 6
a a s d f c
z s    g qq

I wrote the following script in Perl to split data columnwise:

#!/usr/bin/perl
use strict;
use warnings;
#use Text::CSV;

my $file = $ARGV[0] or die "Need to get CSV file on the command line"; 
open(my $data, '<', $file) or die "Could not open '$file' $!";
while (my $line = <$data>) {
 chomp $line;
 my @fields = split " " , $line;
 print "$fields[2]\n";
}

when I run the command, I get the following output

3
s
g

when I should be getting the output as:

3
s

there should be a blank space in 3rd row. The script shifts the values of other column to fill the blank column.

Upvotes: 0

Views: 2860

Answers (2)

ysth
ysth

Reputation: 98453

split ' ' is a special split feature that works like split /\s+/ (except that leading empty fields are discarded). Since you want to split on each tab, not on groups of one or more whitespace characters, you should do so with split /\t/.

Upvotes: 4

serenesat
serenesat

Reputation: 4709

Delimiter is tab, so use tab \t to split instead of space:

#!/usr/bin/perl
use warnings;
use strict;

open my $data, '<', "file.txt" or die "Could not open file: $!";
while (my $line = <$data>)
{
    chomp $line;
    my @fields = split ("\t", $line);
    print "$fields[2]\n";
}

Output:

3
s

Note: There is a blank line after 's' in output (i.e. 3rd line).

Upvotes: 2

Related Questions