Rafael Nguyen
Rafael Nguyen

Reputation: 65

How to fetch text file to array in perl

I have a text file without header as bellow format:

2017-03-13 00,r1,306011,306011,OK,Allgood.
2017-03-13 01,r2,20369,20369,OK,Allgood.
2017-03-13 02,r3,283751,283751,OK,Allgood.
2017-03-13 03,r4,53017,53017,OK,Allgood.

How to fetch this file to array in perl ? I want to print out them with the looping.

my $s_size = scalar(@array);
for(my $i=1; $i<=$s_size;$i++)
{
    print ("$array[$i][0]\n");
    print ("$array[$i][1]\n");
}

The expected result:

2017-03-13 00
2017-03-13 01
2017-03-13 02
2017-03-13 03
r1
r2
r3
r4

Upvotes: 0

Views: 152

Answers (3)

BOC
BOC

Reputation: 1139

I think there are some mistakes in the expected result and the printing loop. Here is how I would do it:

my $filename='/path/test.txt';
open (my $fh, '<', $filename) or die "Can't open $filename: $!";
my @array;
while (my $line = <$fh>) {
    chomp $line;
    push @array, [split ',', $line];
}

my $s_size = scalar(@array);
for(my $i=0; $i<$s_size;$i++)
{
print ("$array[$i][0]\n");
print ("$array[$i][1]\n");
}

the result is:

2017-03-13 00
r1
2017-03-13 01
r2
2017-03-13 02
r3
2017-03-13 03
r4

We can also do it in one line if you like:

my @array = map {chomp; [split ',']} <>;

Upvotes: 1

clt60
clt60

Reputation: 63902

One of more possible solutions could be

use 5.014;
use warnings;

my @lines;
while(<>) {
    chomp;
    push @lines, [split /\s*,\s*/];
}
say $_->[0] for @lines;
say $_->[1] for @lines;

output

2017-03-13 00
2017-03-13 01
2017-03-13 02
2017-03-13 03
r1
r2
r3
r4

As @Sobrique and also @BOC said, you can use

my @lines = map { chomp; [split /,/] } <>;
say $_->[0] for @lines;
say $_->[1] for @lines;

and finally by

  • using a the Text::CSV module
  • having a $filename
use 5.014;
use warnings;

use Text::CSV;

my $filename = "xd.csv";

my $csv = Text::CSV->new({auto_diag => 1, binary => 1});

open my $fh, '<', $filename or die "$filename: $!";
my $lines = $csv->getline_all($fh); #note the arrayref
close($fh);

say $_->[0] for @$lines;
say $_->[1] for @$lines;

Upvotes: 2

yoniyes
yoniyes

Reputation: 1020

I think there's some mix-up in what you request. It seems your expected output doesn't match in any way the output your code is intended to give. If we keep to the code, this will give you your output (given this filename):

use strict;
use warnings;

my $filename = '/path/to/file';
open my $FILE, '<', $filename or die $!;

while(my $line = <$FILE>) {
    chomp $line;
    my @array = split(/,/, $line);
    print "$array[0]\n";
    print "$array[1]\n";
}
close $FILE;

This simplifies your code. If you want it to be as your expected output, simply push @array2, $array[1] (here, @array2 is a new array you need to declare) and print it after the while loop.

Upvotes: 1

Related Questions