0

My question is regarding extraction of data from a file in Perl. In the attached file there is standard format of net list. After running the program I got the elements into an array @name_gate but when I tried to print @name_gate[0] instead of the 1st element, I got the whole first column, similarly for @name_gate[1], the second column.

So the problem is I have again got a string in @name_gate[0] which I want to access element by element.

my @ind;
my $index=0;
my $file = 'netlist.txt';
my $count=0;
my @name_gate;
open my $fh,'<',$file or die "could not open the file '$file' $!";

while (my $line = <$fh>) 
     {
         chomp $line;
         @name_gate = split (/ /,$line); #transforming string into arrays

         print "@name_gate[0]";
     }

The above code prints the whole column 1 2 3 4 up to 14. How can I extract a single element like 1 or 2 or 14 etc. Here is the current output

xxfelixxx
  • 6,512
  • 3
  • 31
  • 38
Blackwind
  • 1
  • 2
  • 2
    first element is a scalar try `$name_gate[0]` – salparadise Mar 27 '17 at 04:33
  • Always have `use warnings;` and `use strict;` at the beginning of all programs. With warnings on you would get `Scalar value @ary[0] better written as $ary[0] at ...` – zdim Mar 27 '17 at 04:52
  • No,it prints out the same thing as before all elements of 1st column. – Blackwind Mar 27 '17 at 04:52
  • You get all of the elements of the 1st column because you are iterating over all of the lines in your file. Isn't that what you want? Or do you really just want the first element from the first line? – xxfelixxx Mar 27 '17 at 04:55
  • 1
    Please show a few lines of input. But please not a picture, but rather edit the question and copy and paste them at the end. – zdim Mar 27 '17 at 04:58
  • Without seeing your input file, it's impossible to do anything but guess here. Your code looks fine (well, other than using `@name_gate[0]` instead of `$name_gate[0]` which won't cause the behaviour you describe) so I suspect the problem is that your data isn't quite what you think. Two obvious possibilities: the line end characters are from a different operating system or the field separators aren't single spaces. – Dave Cross Mar 27 '17 at 07:57

1 Answers1

3

@name_gate[0] it is not a main problem. Because with warnings (Scalar value @ary[0] better written as $ary[0] at) it will give the result.

I thought your problem is in split. Because your input file having multiple spaces or tab separated. So please include \s+ or better use \t. You will get the result.

Then always put use warnings and use strict in top of the program,

while (my $line = <$fh>) 
{
     chomp $line;

      #my @name_gate = split (/ /,$line); #transforming string into arrays

      my @name_gate = split (/\s+/,$line);

      #print "@name_gate[0]\n";

      print "$name_gate[0]\n";

}
mkHun
  • 5,891
  • 8
  • 38
  • 85