I have a text file formatted so that there are 3 numbers, separated by a space, on each line.
I need my Perl code to read this file sideways and ignore the spaces.
At the moment it is reading downwards and ignoring all the rest of the contents:
2 5 10
3 30 60
My code would only read 2 and 3.
use strict;
open (FILE, shift);
my @contents = <FILE>;
my $first = splice @contents, 0;
my $second = splice @contents, 1;
my $third = splice @contents, 2;
my $total = $first + $second + $third;
print "$total\n";
You didn’t specify what you want. I’m guessing you want to values from each row, one row at a time. (2, 5 and 10, then 3, 30 and 60)
I’m not sure that you know what
splicedoes.should be
You didn’t specify you only wanted to remove one item, and you didn’t account for the index shift that occurs from earlier removals from the array.
There’s probably no reason to remove the elements from the array, so that’s silly code. You could simply use
Or even
So how does one get the fields from a line?
split.All together,
But that can be simplified.
References:
splicesplit