how to save data in array form in perl?

I want to print each data in one line as in array form. My input is shown below:

Mn1 o1 a ss vs nsvt 0.17 0.02 $$UNI
Mn2 o1 b n2 vs nsvt 0.272 0.02 $$UNI
Mn3 n2 c ss vs nsvt 0.272 0.02 $$UNI
Mp1 o1 a n1 vc  svt 0.476 0.02 $$UNI
Mp2 n1 b cc vcc xsvt 0.51 0.02 $$UNI
Mp3 n1 c cc vc svt 0.51 0.02 $$UNI
Mibit0e[0].g00.xxx camoutbit0p0 ibit0e[0].bit camblp0y[0] vs svt  
+ 0.068 0.02 
Mibit0e[0].g00.bbb camoutbit0p0 ibit0e[0].bitx camblp0y[0] vc  
+ pvt 0.068 0.02 
Mibit0e[0].g01.qqq camoutbit0p1 ibit0e[0].bit camblp1y[0] vs nsvt  
+ 0.068 0.02 
Mibit0e[0].g01.sss camoutbit0p1 ibit0e[0].bitx camblp1y[0] vc  
+ pxt 0.068 0.02 

current output:

 Mn1 o1 a ss vs nsvt 0.17 0.02 $$UNI
 Mn2 o1 b n2 vs nsvt 0.272 0.02 $$UNI
 Mn3 n2 c ss vs nsvt 0.272 0.02 $$UNI
 Mp1 o1 a n1 vc  svt 0.476 0.02 $$UNI
 Mp2 n1 b cc vcc xsvt 0.51 0.02 $$UNI
 Mp3 n1 c cc vc svt 0.51 0.02 $$UNI
 Mibit0e[0].g00.xxx camoutbit0p0 ibit0e[0].bit camblp0y[0] vs svt  0.068 0.02 
 Mibit0e[0].g00.bbb camoutbit0p0 ibit0e[0].bitx camblp0y[0] vc  pvt 0.068 0.02 
 Mibit0e[0].g01.qqq camoutbit0p1 ibit0e[0].bit camblp1y[0] vs nsvt  0.068 0.02 
 Mibit0e[0].g01.sss camoutbit0p1 ibit0e[0].bitx camblp1y[0] vc  pxt 0.068 0.02 

when I change to print"$p[2]\n", the output is shown below:

Mn3 n2 c ss vs nsvt 0.272 0.02 $$UNI.

but my expected output are all data in third coluumn :

a
b
c
a
b
c
ibit0e[0].bit
ibit0e[0].bitx
ibit0e[0].bit
ibit0e[0].bitx

current code:

#!/usr/bin/perl
use strict;
use warnings;
my $k;
my $f;
my $a;
my $v;
my @p;
my @a;
my @array;
my $x;
my $h;
my @m;
my @n;
my $p;
open ($f,'<',"test.txt");
while($k = <$f>)
{
chomp $k;
 if ($k=~ m/^M/)
  {
   my @h= split (/\s+/,$k);
   my $h= @h;
  if($h!=9)
   {
   my $v = <$f>;
   $v =~ s/\+//;
   $x = "$k $v";
   push @p,$x;
   }
  else 
   {
  $x = "$k\n";
  push @p,$x;
   }
  }
}
close $f;
print "@p\n";

when i change to print"$p[2]\n", the output is Mn3 n2 c ss vs nsvt 0.272 0.02 $$UNI. but the output I want is the third column, not the third row. my expected output as shown below:

a
b
c
a
b
c
ibit0e[0].bit
ibit0e[0].bitx
ibit0e[0].bit
ibit0e[0].bitx

Upvotes: 2

Views: 80

Answers (1)

Andrey
Andrey

Reputation: 1818

You can simplify the code this way

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

open (my $f,'<',"test.txt");
while(my $k = <$f>)
{
    chomp $k;
    print ((split(/\s+/,$k))[2] . "\n") if ($k=~ m/^M/);
}
close $f;

Second version combines the lines into array and then prints the column you need

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

my @data;
open (my $f,'<',"test.txt");
while(my $k = <$f>) {
    chomp $k;
    if ($k =~ /^M/) {
        push(@data, $k);
    }
    elsif($k =~ /^\+(.+)/) {
        $data[-1] .= $1;
    }
    else {}
}
close $f;
foreach my $line (@data) {
    print ((split(/\s+/,$line))[2] . "\n");
}

You could also split first and then create the array of array references to make the data structure mentioned in the comment.

Upvotes: 3

Related Questions