Jakob Kofoed wrote:
I have a file with some navigation (x and y's) and needed to fill in point between exiting points. My in put file: 600000 6174210 600017 6174213 600028 6174206 600035 6174216 600045 6174209 For calculation I need to use line 1 and 2 for calculating one point and then line 2 and 3 and so on ... I solved it by using Xaviers tip on Tie::File: use Tie::File; tie my @line, 'Tie::File', $ARGV[0] or die "could not open $ARGV[0]: $!"; my $cnt1 = 0; my $cnt2 = 0; while ( $cnt1 < $ARGV[1] ) { $cnt2++; #print " $cnt1 $cnt2\n"; my @rec1 = split(' ', $line[$cnt1]); my @rec2 = split(' ', $line[$cnt2]); my $newin = (($rec1[0] - $rec2[0]) / 2) + $rec2[0]; my $newxl = (($rec1[1] - $rec2[1]) / 2) + $rec2[1]; print "@rec1\n"; print "$newin $newxl\n"; $cnt1 = $cnt2; }
This code will not print the very last line of the file. You need to add the line (below) after you exit the while loop. print "@rec2\n";
where $ARGV[1] is the number of lines in the file.
How do you know beforehand the number of lines in the file? By the way, I think that the test in the while loop should be: while ( $cnt1 < $ARGV[1] - 1 ) {
Could I have used an array as you mentioned in the bottom of your comment?
Yes, you could have (and not needed both: Tie::File and $ARGV[1]). The code below
reads the file in $ARGV[0] into @line my @line = <>; while ($cnt1 < $#line) { etc. As a last note, I wouldn't have read the whole file into an array (which is often called 'slurping' a file) and wouldn't have needed to keep the 2 count variables. Instead, I used $first and $second to capture the needed lines. This way, if you are dealing with a very large file, you only read 1 line at a time into memory instead of 'slurping' the entire file into an array. But the method you chose should work as well (if not a huge file). :-) #!/usr/bin/perl use strict; use warnings; my $first; my $second; while (<>) { chomp; $first = $_, next unless $first; $second = $_; my @rec1 = split ' ', $first; my @rec2 = split ' ', $second; my $newin = (($rec1[0] - $rec2[0]) / 2) + $rec2[0]; my $newxl = (($rec1[1] - $rec2[1]) / 2) + $rec2[1]; print "$first\n"; print "$newin $newxl\n"; $first = $second; } print "$second\n"; Chris -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>