i'm trying to open a file with three or more columns and an undetermined, but finite number of rows. I want to define an array for each row with each element of the row as a sub array. The columns are separated by tabs or spaces.
#!/usr/bin/perl -w
use warnings;
use strict;
open (FILE, xyz.txt) or die " $!";
our @lines<FILE>;
chomp @lines;
close (FILE);
for (@lines) {
$/="\t|' '"; # field sperator is either tab or ' '
our @lines=([split / /, $_]);
}
print "First element \'$lines[0][0]\'\n";
print "Second element \'$lines[0][1]\'\n";
print "Third element \'$lines[0][2]\'\n";
print "First element \'$lines[1][0]\'\n";
...
or somehow make a hash reference to each element of the row
...
print "First element \'$lines{0}->{first]\'\n";
print "Second element \'$lines{0}->{second}\'\n";
print "Third element \'$lines{0}->third}\'\n";
print "First element \'$lines{1}->{first}\'\n";
...
@lines = ( {
AA => "454.23.23.232"
BB => "12x3.12z34b.342sd3.sds"
CC => "aSDGgsOds"
},
{
AA => "354.23.2113.232"
BB => "4z3x3.134b.332sSSsd3.Ccsds"
CC => "aSDffGgds"
},
{
AA => "22454.23.23.20032"
BB => "12x333.123ww4b.342sed3.sdsO"
CC => "BSDGgds"
}
);
but my syntax isn't working...
open(FILE, '<x.txt') or die $!;
my @lines;
while (<FILE>) {
chomp;
my ($BB,$AA,$CC)=split(/\s+/,$_);
$lines[$_]={BB=>$BB,AA=>$AA,CC=>$CC};
}
close FILE;
print $lines[0]{BB},"\n";
...
open(FILE, '<x.txt') or die $!;
my @lines;
while (<FILE>) {
chomp;
my ($BB,$AA,$CC)=split(/\s+/,$_);
@lines = (@lines, {BB=>$BB,AA=>$AA,CC=>$CC});
}
close FILE;
print $lines[0]->{BB},"\n";
...
nice, what id I have missing lines or columns in the data. What is the syntax to shift to next element/key if one is missing while still separating by every new line?
For the missing line, you will need to check whether the line is empty in the loop and skip over. This is an easy exercise. Try to find out yourself first.
Missing column sometimes cannot be checked. It depends on how irregular your data set can be.