in reply to extracting and using values from a matrix file
Your code with one comment:
for(my $i = 0; $i < @filecontents; $i++) { # place each line in file # into another array # @line = split(/\,/, $filecontents[$i]); # XXX ^------ do you really mean comma?
In the following, I'll asume the fields are separated by blanks. No need to backslash a comma, BTW.
Ok, what shall we do with @line? assigning to it on each iteration overwrites the previous content.
We need a multidimensional array - a matrix. References (see perlreftut) are handy for that.
# [] constructs an anonymous array, so we use that. # several ways to do it - choose any (not all :-) my $anon_array = []; # gimme an anonymous array and # assign it to $anon_array @$anon_array = @line; # assign to the anonymous array push(@matrix, $anon_array); # shortcut: $anon_array = [ @line ]; push(@matrix, $anon_array); # compacting further: split returns a list, use that # to populate an anonymous array on the fly, push that # (the SCALAR value which is an array reference) onto # the array @matrix push(@matrix, [split(/\s+/, $filecontents[$i])]); }
But why do we have all more than one time in memory? (one array holding the lines, another holding the broken-up structure) - back to the file reading.
We can save many a malloc() and brk() and typing just saying
my @matrix; while (<INPUT>) { chomp; # you forgot that - remove trailing newline char push(@matrix, [split]); }
because while(<INPUT>) assigns to $_, and split by default breaks $_ with the pattern /[ \t]+/, i.e. on one or more whitespace characters.
If you use the <> magic, perl opens each file in @ARGV for you in order, and reads those; using it, your code boils down to
#!/usr/bin/perl use strict; my @matrix; while (<>) { chomp; # you forgot that - remove trailing newline char push(@matrix, [split]); }
If you want to read just one file, you can truncate @ARGV assigning to the array length (well, not quite: the arrays last index):
$#ARGV = 0; # @ARGV now holds only one element (the first at index 0)
How do you get your data back? The following prints the value in the 4th column of the 7th line (again, see perlreftut):
print $matrix[7]->[4],"\n";
--shmem
_($_=" "x(1<<5)."?\n".q·/)Oo. G°\ /
/\_¯/(q /
---------------------------- \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
|
|---|