john.tm has asked for the wisdom of the Perl Monks concerning the following question:
I have a file which i run a foreach loop on, then save it. reopen it and remove some dupliacte lines based on certaian fields. how can i run this without the saving and reopening of the file in the middle section each time.
#!/usr/bin/perl use strict; use warnings; #use diagnostics; my $file = "c:\\tmp.txt"; open( my $fh, "<", $file ) or die $!; my $OUTNET = "c:\\NETtmp.txt"; open( OUTPUT, ">", "$OUTNET" ) or die $!; my @array; foreach (<$fh>) { chomp ; if ( $_ =~ m/^\s+\d/ ) { $_ =~ s/^\s+//g; $_ =~ s/\s+$//g; $_ =~ s/\s+/,/g; push @array, "s_"; print " $_ \n"; printf OUTPUT "$_ \n"; } } close OUTPUT; my $file2 = "c:\\NETtmp.txt"; my $OUTNET2 = "c:\\final.txt"; open my $in, '<', $file2 or die $!; open my $out, '>', $OUTNET2 or die $!; seek $in, 0, 0; my %hash; while (<$in>) { my $key = join ',', ( split /,/ )[ 1, 2, 3, 4 ]; printf $out $_ unless $hash{$key}++; } close $out; close $in;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Perl script run foreach loop and sort without having to save and reopen the filehandle each time. (SMoP)
by tye (Sage) on Dec 15, 2014 at 21:44 UTC | |
|
Re: Perl script run foreach loop and sort without having to save and reopen the filehandle each time.
by toolic (Bishop) on Dec 15, 2014 at 21:04 UTC | |
|
Re: Perl script run foreach loop and sort without having to save and reopen the filehandle each time.
by GotToBTru (Prior) on Dec 15, 2014 at 21:01 UTC |